There may be times where one may think that I can extend parent class instead of implementing interface. Lets see whats When to choose inheritance over an interface and interface over inheritance.
inheritance over an interface
The main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for the evolution of APIs. Once you ship an interface, the set of its members is fixed forever. Any additions to the interface would break existing types implementing the interface.
A class offers much more flexibility. You can add members to classes that you have already shipped. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function unchanged.
interface over inheritance
Lets take the following code
Mammal.java
public abstract class Animal
{
public void abstract mate();
public void abstract feed();
}
Now the above abstract class has two methods mate() and feed().
public class Dog extends Animal
{
}
public class Cat extends Animal
{
}
Now we have Dog and Cat concrete classes extending Animal.
we have few more classes extending Animal
public class Giraffe extends Animal{}
public class Rhinoceros extends Animal{}
public class Hippopotamus extends Animal{}
Now the classes Dog and Cat are pet animals. So it should implement pet behavior. This can be done in two ways.
- By defining isPet() method in base class and overriding in child class
- By implementing pettable interface.
Now implementing interface is easy compared to overriding method defined in base class because
- Interface favours clean code. Defining and Overriding the class may increase code redundancy
-
Now you get a parakeets which is again a pet and could also fly.If you are inheriting the base class then you need to add canFly() method in base class and set it to return false and override in the parakeets class to return true.
public class parakeets extends Animal
{
.
.
public boolean canFly()
{
return true;
}
}
Instead you can declare a interface flyable and implement the interface method without making changes to base class
public class parakeets extends Animal implements flyable
{
.
.
public boolean canFly()
{
return true;
}
}
- Interface may be completely not related to class in which it is implemented. Say lets define a carpenter ants class which always moves one after another.Now this can be represented to implement queuing interface which has nothing to do with other animals other then carpenter ants since only ants of this type follows a queue system when they migrate from one place to another