What is the main difference between Inheritance and Polymorphism? What is the main difference between Inheritance and Polymorphism? java java

What is the main difference between Inheritance and Polymorphism?


Inheritance is when a 'class' derives from an existing 'class'. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has. There are some details around the access modifiers you put on the fields/methods in Person, but that's the basic idea. For example, if you have a private field on Person, Student won't see it because its private, and private fields are not visible to subclasses.

Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person, which has a read method, and you have a Student which extends Person, which has its own implementation of read, which method gets called is determined for you by the runtime, depending if you have a Person or a Student. It gets a bit tricky, but if you do something like

Person p = new Student();p.read();

the read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p is Student.

Note that details differ among languages. You can do inheritance in javascript for example, but its completely different than the way it works in Java.


Inheritance refers to using the structure and behavior of a super class in a subclass.

Polymorphism refers to changing the behavior of a super class in the subclass.


Polymorphism: The ability to treat objects of different types in a similar manner. Example: Giraffe and Crocodile are both Animals, and animals can Move. If you have an instance of an Animal then you can call Move without knowing or caring what type of animal it is.

Inheritance: This is one way of achieving both Polymorphism and code reuse at the same time.

Other forms of polymorphism:There are other way of achieving polymorphism, such as interfaces, which provide only polymorphism but no code reuse (sometimes the code is quite different, such as Move for a Snake would be quite different from Move for a Dog, in which case an Interface would be the better polymorphic choice in this case.

In other dynamic languages polymorphism can be achieved with Duck Typing, which is the classes don't even need to share the same base class or interface, they just need a method with the same name. Or even more dynamic like Javascript, you don't even need classes at all, just an object with the same method name can be used polymorphically.