Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in this case use Interface over Abstract class?

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{
}
like image 534
CodeFarmer Avatar asked Nov 19 '25 03:11

CodeFarmer


1 Answers

You cannot inherit from more than one class (abstract or not), but can implement multiple interfaces

If you were to create abstract classes, you will need one for every combination (n atributes: 2^n possible combination) -- to ensure that each combination can be inherited from, if needed.

If you are using interfaces, you only need to define the n interface (one for each attribute) and implement them as needed.

like image 151
Attila Avatar answered Nov 21 '25 18:11

Attila