What is the main difference between Inheritance and Polymorphism?
Solution 1
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.
Solution 2
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.
Solution 3
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.
Solution 4
The main difference is polymorphism is a specific result of inheritance. Polymorphism is where the method to be invoked is determined at runtime based on the type of the object. This is a situation that results when you have one class inheriting from another and overriding a particular method. However, in a normal inheritance tree, you don't have to override any methods and therefore not all method calls have to be polymorphic. Does that make sense? It's a similar problem to all Ford vehicles are automobiles, but not all automobiles are Fords (although not quite....).
Additionally, polymorphism deals with method invocation whereas inheritance also describes data members, etc.
Solution 5
In Java, the two are closely related. This is because Java uses a technique for method invocation called "dynamic dispatch". If I have
public class A {
public void draw() { ... }
public void spin() { ... }
}
public class B extends A {
public void draw() { ... }
public void bad() { ... }
}
...
A testObject = new B();
testObject.draw(); // calls B's draw, polymorphic
testObject.spin(); // calls A's spin, inherited by B
testObject.bad(); // compiler error, you are manipulating this as an A
Then we see that B inherits spin
from A. However, when we try to manipulate the object as if it were a type A, we still get B's behavior for draw
. The draw
behavior is polymorphic.
In some languages, polymorphism and inheritance aren't quite as closely related. In C++, for example, functions not declared virtual are inherited, but won't be dispatched dynamically, so you won't get that polymorphic behavior even when you use inheritance.
In javascript, every function call is dynamically dispatched and you have weak typing. This means you could have a bunch of unrelated objects, each with their own draw
, have a function iterate over them and call the function, and each would behave just fine. You'd have your own polymorphic draw without needing inheritance.
Related videos on Youtube
Darren Burgess
Recent Graduate of Northumbria University with 1st class Honors in Computing Currently a Graduate at Hewlett-Packard in incident management.
Updated on September 03, 2021Comments
-
Darren Burgess over 2 years
I was presented with this question in an end of module open book exam today and found myself lost. I was reading
Head first Java
and both definitions seemed to be exactly the same. I was just wondering what the MAIN difference was for my own piece of mind. I know there are a number of similar questions to this but, none I have seen which provide a definitive answer.-
Edwin Dalorzo almost 12 yearsSomehow related to this question: Is polymorphism possible without inheritance
-
Tomas almost 10 yearsAlso related: Isn't polymorphism just a side effect of inheritance?
-
-
Muhammad Raihan Muhaimin almost 11 years@ hvgtcodes so in a nutshell, the superclass-subclass relation is inheritance and the concept of implementation of same method in a different way in between parent class and its sub classes, and call them based on situation are Polymorphism,. Am I correct?
-
jaco0646 over 7 yearsDoes this answer imply that polymorphism requires inheritance?
-
Ted Hopp over 7 years@jaco0646 - In the context of Java, I think so. (In other languages, perhaps not so much.) Note that "super class" and "subclass" are used loosely here. Polymorphism could also mean inheritance of behavior specified (but not implemented) in an interface.
-
Scorpiorian83 about 7 years@hvgotcodes but say if
Person
'sread
method is using public access modifier, won'tStudent
objects be able to access them? and thenStudent s = new Student();
won't it be easier? I still don't really quite get the benefits of Polymporphism actually. -
munmunbb over 6 years@hvgotcodes Student s = new Student() would work. But let's say after you wrote a lot of the code using this idea, and later on you realize that you made a mistake. The person is actually not a student, it is a teacher. So you could simply change from Person p = new Student() into Person p = new Teacher(), then it will make your life so much simpler.
-
Ted Hopp over 6 years@AlirezaRahmani - I don't understand your comment. Do you mean that inheritance doesn't involve inheriting both properties and behavior? That would be contrary to how Java (and most class-based, object-oriented languages) define inheritance. From the Java Language Specification, §8.4.8: "A class C inherits from its direct superclass all concrete methods
m
(bothstatic
andinstance
) of the superclass for which ..." (followed by details on inheritance). Sounds like "code reuse" to me. -
Alireza Rahmani khalili over 6 years@TedHopp Inheritance is primarily a polymorphic tool, but some people, much to their later peril, attempt to use it as a way of reusing/sharing code. The rationale being "well if I inherit then I get all the methods for free", but ignoring the fact that these two classes potentially have no polymorphic relationship.
-
Ted Hopp over 6 years@AlirezaRahmani - In Java (which is what OP specifically asked about, according to the tags), class inheritance most definitely involves inheriting behavior. That's part of the language definition. The fact that this can be misused as you describe is one of the weaknesses of Java. (A related weakness involved declaring classes to implement interfaces simply to import the constants defined in the interface. Eventually the Java designers introduced
import static
to eliminate this misuse of interfaces.) For pure polymorphism in Java, the tool to use is interfaces, not class inheritance. -
Alireza Rahmani khalili over 6 years@TedHopp inheriting behavior? what do you mean? imagine in a real world can you inherit you father eyes? and about java, there is a discussion: If you could do Java over again, what would you change? - I would avoid implementation inheritance whenever possible. -James Gosling (Java's inventor).
-
Ted Hopp over 6 years@AlirezaRahmani - I was using "inheriting behavior" in the sense of "behavioral subtyping" as introduced by Bertrand Meyer (in his book Object-Oriented Software Construction) and as used in expressing the Liskov substitution principle. Please be aware that my answer was directed at the difference between inheritance and polymorphism in Java as it is today, not at answering the very broad question of what's the right way to do OO languages.
-
Alireza Rahmani khalili over 6 yearsLet us continue this discussion in chat.
-
Ted Hopp over 6 years@Ravindrababu - Thanks for the edit, but I've reverted to the U.S. spelling for behavior. :)
-
towry about 6 years@jaco0646 In swift, no.
-
Santanu Sahoo about 6 years@TedHopp this is not true for Compile time polymorphism as there is no super calss involves
-
PerfectContrast about 5 yearsMy question here would by why would you want to use
Person p = new Student();
instead ofStudent p = new Student();
? -
Ted Hopp almost 5 years@FooBar - Yes, static polymorphism does not necessarily involve a superclass. I just have a hard time thinking of compile-time method binding as polymorphism at all (even though it's trendy to use that terminology).
-
savante almost 4 years@PerfectContrast I think it is useful when you want to have student, driver, teacher etc. as Person and you group them under a List or something. So when you call 'read' for all, everyone calls their own 'read' method.
-
kaushalpranav almost 4 yearsIf we are going to write Person p = new Student() in the code, and we know that Student extends Person, why do we need to decide which function (here the read() in Student) is called at run time rather than at compile time?
-
veritas over 3 years@PerfectContrast IF you want to write a sort method that is common to all kinds of persons - student, driver, teacher etc. Doing sort(List<Person> personList){ //do something} is better than having 4 sort methods for each Person type.
-
veritas over 3 years@kaushalpranav - compile time simply means program shouldn't throw errors. run time means that the user decides e.g he presses a button on UI saying "sort my drivers", the UI would send some key e.g driver to app server i.e Java. At server side, code would remain the same sort(personList). --> this code will be in some Factory Person p1 = new Driver(); -->Person p2 = new Driver(); personList.add(p1).add(p2) --- this code would be common -- Collection,sort(personList). This psuedo code would not change whether sort key from UI is driver or teacher or student.
-
M. Al Jumaily over 3 yearsRegarding inheritance, I would appreciate it if you can add "... the behaviour is inherited (assuming we don't override anything in the subclass)".