Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between inheritance and polymorphism

I was studying about polymorphism. I couldn't determine the analogy in Java about these two features.

Let's say Animal class is a concrete superclass with Cat and Dog as its subclasses. I know that this is a case of inheritance. But isn't Cat and Dog classes, polymorphs of Animal class?

I am well aware of interfaces in Java. I couldn't understand why interfaces are used instead of concrete classes to explain polymorphism. It could be that the whole purpose of creating interface is to create polymorphs but I want to know why interfaces and not concrete classes?

like image 704
h-rai Avatar asked Sep 04 '26 10:09

h-rai


1 Answers

Inheritance

class Animal{
  public void speak(){ System.out.println("Speaking something");}
}

class Person extends Animal{
 @Override
 public void speak(){ System.out.println("Hello..");}
}  

Polymorphism

Animal a  = new Person();
a.speak();// Hello

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class [..]


Why Interface ?

You know what needs to be done, but you want implementers to decide how to do it, You will let implementer implement the stuffs forcefully

  • when-best-to-use-an-interface-in-java
like image 141
jmj Avatar answered Sep 06 '26 01:09

jmj