Method Signatures
Strictly speaking a interface method and an abstract method are similar. In both cases the modifier in the sub class or implementing class must be equal or less restrictive than the super class. Even there signature is very similar. The key difference is: At the class level they are defined by different key words and the abstract class can have impementation methods. Both interface and abstract class access modifiers must be public. This has significant impications on object model and design.
Examples of signatures:
protected abstract void communicates(); //from abstarct class
public abstract String tastesLikeChicken(); //from interface
Abstract Class
An abstact class is best used when the functionality belongs in the heirachy of the class and you want to enforce a contract in this heirarchy.
Example: implements and defines methods that have to do with all animals
public abstract class Animal
{
protected abstract void communicates();
protected abstract void moves();
protected abstract void eats();
protected String isAlive(){ return "yes"; } //implemented method
}
public class Dog extends Animal abstract methods
{
public void communicates()
{
System.out.println("Barking!!!");
}
public void wagsTail(){ //some code that is specific to a dog };
...
}
Interface
An interface is best used when the functionality belongs out side a classes heirarchy. Again you want to enforce a contract with the interface. When mixed with other patterns such as IoC (e.g. Spring) this can become a very powerfull tool.
Example: defines methods not related to being an animal
public interface eatable
{
public String tastesLikeChicken();
}
public class Dog extends Animal implaments eatable, domestic
{
public String tastesLikeChicken(){ return "yes"; }
public void communicates()
{
System.out.println("Barking!!!");
}
...
}
The interface feature in Java has huge ramifications on desgin. It also solves a anti-pattern common to C/C++ known as the diamond inheitance anti-pattern. Remember a class can implament many interfaces but only extend one parent in Java.
Hope you find this informative. PS: I wound never eat my little mutt Luna :) even if she did taste like chicken.
No comments:
Post a Comment