I was reading a blog post here: http://codeofdoom.com/wordpress/2009/02/12/learn-this-when-to-use-an-abstract-class-and-an-interface/
public interface Actor{
Performance say(Line l);
}
public interface Director{
Movie direct(boolean goodmovie);
}
public interface ActorDirector extends Actor, Director{
...
}
It says:
In reality, there are Actors who are also Directors. If we are using interfaces rather than abstract classes.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.
Question: why abstract class is better here ? and why 2^n ?
public abstract class ActorDirector implements Actor,Director{
}
I think you misunderstood the post: the author is not arguing that an abstract class is better in this situation – on the contrary, he is arguing that an interface is a better fit.
As far as
2^n(or more precisely2^n-1) goes, the number comes from realization that if you havenorthogonal behavior contracts, you can make2^n-1non-empty combinations from them. If you use interfaces to add contracts to classes that implement them, you need only as many interfaces as there are behaviors: the user will be able to make combinations of behaviors that he chooses to implement, up to2^n-1. If you were to try achieving the same flexibility with abstract classes, you would end up creating not only your desired implementations, but also all the intermediate ones required all the way to a single root, because Java lets you inherit classes only one at a time.