Say I have an Animal class, and I want different classes and functionality for each kind of animal. There are two ways of doing this:
Method overriding through inheritance:
public class Animal { public void sound() {} } public class Dog extends Animal { public void sound() { System.out.println("bark"); } } public static void main(String[] args) { Animal dog = new Dog(); dog.sound(); }
By extending the
Animal
abstract class:abstract public class Animal { abstract public void sound(); } public class Dog extends Animal { public void sound() { System.out.println("bark"); } } public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); }
So why do we use abstract classes at all, when the exact same thing is being done by the first method? I understand why we use interfaces - it establishes a contract that any class implementing it has to have certain methods and attributes. But what is the use of an abstract class, when the same thing can be achieved through simple inheritance?