How to decide whether to use Interface or Abstract Class ?

#1
Choosing Interfaces and Abstract Classes is not an either/or proposition. If you need to change your design, make it an Interface. However, you may have Abstract Classes that provide some default behavior. Abstract Classes are excellent candidates inside of application frameworks.

Abstract Classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an Abstract Class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the Abstract Base Class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an Abstract Class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the Abstract Class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

Example :

abstract class Human {

void hand(){
System.out.print("Two Hands");
}

void leg(){
System.out.print("Two Leg");

void head(){
System.out.print("One Head")
}
void language();
void language();

}

public class southIndia extends Human{

void dressCode(){
//Traditional dress Code
}
void language(){
// Telugu, Tamil, Kanada,Kokani
}
public class NorthIndia extends Human{

void dressCode(){
// Traditional Dress Code of North India
}
void language(){
//Hindi
}

}

when interface

Birds are flying in Air and also Aeroplane.

Both have a method fly(), but they have no similarities.

in this case prefarable interface

interface flying{
void fly();
}

public class Bird implements flying{

public void fly(){
// do ur stuff

}

public class Aeroplane implements flying{
void fly(){

// stuff
}
}
 
Last edited:
#2
1. You apprehend that different classes would apparatus your interface. ...
2. You demand to specify the behavior of a accurate abstracts type, but not anxious about who accouterments its behavior.
3. You demand to booty advantage of assorted inheritances.
 
Top