Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
A Java class can implement multiple interfaces but it can extend only one abstract class.
Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
When to prefer an interface
Back when I wrote about the importance of composition, I mentioned that it is extremely useful when you don’t want a massive hierarchical type framework. The same applies to interfaces. This isn’t my example, but its the best one Ive come across. Lets say you have an interface for a Director and another interface for a Actor.
public interface Actor{
Performance say(Line l);
}
public interface Director{
Movie direct(boolean goodmovie);
}
In reality, there are Actors who are also Directors. If we are using interfaces rather than abstract classes, we can implement both Actor and Director. We could even define an ActorDirector interface that extends both like this:
public interface ActorDirector extends Actor, Director{
...
}
We could achieve the same thing using abstract classes. Unfortunately the alternative would require up to 2^n (where n is the number of attributes) possible combinations in order to support all possibilities.
No comments:
Post a Comment