We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.
Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.
Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.
But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.
So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.
So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.
You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).
I will share with you a piece of code: You try it with different sets of inputs and look at the results.
class AnimalClass {
public void doEat() {
System.out.println("Animal Eating...");
}
public void sleep() {
System.out.println("Animal Sleeping...");
}
}
public class Dog extends AnimalClass implements AnimalInterface, Herbi{
public static void main(String[] args) {
AnimalInterface a = new Dog();
Dog obj = new Dog();
obj.doEat();
a.eating();
obj.eating();
obj.herbiEating();
}
public void doEat() {
System.out.println("Dog eating...");
}
@Override
public void eating() {
System.out.println("Eating through an interface...");
// TODO Auto-generated method stub
}
@Override
public void herbiEating() {
System.out.println("Herbi eating through an interface...");
// TODO Auto-generated method stub
}
}
Defined Interfaces :
public interface AnimalInterface {
public void eating();
}
interface Herbi {
public void herbiEating();
}