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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With