What is the main difference between Inheritance and Polymorphism?
Asked Answered
C

18

202

I was presented with this question in an end of module open book exam today and found myself lost. I was reading Head first Javaand 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.

Cavalier answered 10/6, 2011 at 15:0 Comment(2)
Somehow related to this question: Is polymorphism possible without inheritanceUndersea
Also related: Isn't polymorphism just a side effect of inheritance?Zolazoldi
C
321

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.

Conscience answered 10/6, 2011 at 15:4 Comment(8)
@ 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?Giustino
@Conscience but say if Person's read method is using public access modifier, won't Student objects be able to access them? and then Student s = new Student(); won't it be easier? I still don't really quite get the benefits of Polymporphism actually.Reformation
@Conscience 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.Rogovy
My question here would by why would you want to use Person p = new Student(); instead of Student p = new Student(); ?Weeks
@Weeks 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.Philippeville
If 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?Seism
@Weeks 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.Mycenaean
@Seism - 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.Mycenaean
B
241

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.

Bhutan answered 10/6, 2011 at 15:5 Comment(12)
Does this answer imply that polymorphism requires inheritance?Jessejessee
@Jessejessee - 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.Bhutan
@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 (both static and instance) of the superclass for which ..." (followed by details on inheritance). Sounds like "code reuse" to me.Bhutan
@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.Jaramillo
@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.Bhutan
@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).Jaramillo
@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.Bhutan
Let us continue this discussion in chat.Jaramillo
@Ravindrababu - Thanks for the edit, but I've reverted to the U.S. spelling for behavior. :)Bhutan
@Jessejessee In swift, no.Portwin
@TedHopp this is not true for Compile time polymorphism as there is no super calss involvesSaundrasaunter
@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).Bhutan
C
77

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.

Coition answered 10/6, 2011 at 15:16 Comment(0)
S
18

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.

Spiny answered 10/6, 2011 at 15:3 Comment(0)
F
15

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.

Frulla answered 10/6, 2011 at 15:18 Comment(0)
W
13

Polymorphism: Suppose you work for a company that sells pens. So you make a very nice class called "Pen" that handles everything that you need to know about a pen. You write all sorts of classes for billing, shipping, creating invoices, all using the Pen class. A day boss comes and says, "Great news! The company is growing and we are selling Books & CD's now!" Not great news because now you have to change every class that uses Pen to also use Book & CD. But what if you had originally created an interface called "SellableProduct", and Pen implemented this interface. Then you could have written all your shipping, invoicing, etc classes to use that interface instead of Pen. Now all you would have to do is create a new class called Book & CompactDisc which implements the SellableProduct interface. Because of polymorphism, all of the other classes could continue to work without change! Make Sense?

So, it means using Inheritance which is one of the way to achieve polymorphism.

Polymorhism can be possible in a class / interface but Inheritance always between 2 OR more classes / interfaces. Inheritance always conform "is-a" relationship whereas it is not always with Polymorphism (which can conform both "is-a" / "has-a" relationship.

Washbowl answered 16/12, 2012 at 0:55 Comment(0)
F
6

Inheritance is more a static thing (one class extends another) while polymorphism is a dynamic/ runtime thing (an object behaves according to its dynamic/ runtime type not to its static/ declaration type).

E.g.

// This assignment is possible because B extends A
A a = new B();
// polymorphic call/ access
a.foo();

-> Though the static/ declaration type of a is A, the actual dynamic/ runtime type is B and thus a.foo() will execute foo as defined in B not in A.

Forsook answered 10/6, 2011 at 15:8 Comment(0)
G
3

Polymorphism is an approach to expressing common behavior between types of objects that have similar traits. It also allows for variations of those traits to be created through overriding. Inheritance is a way to achieve polymorphism through an object hierarchy where objects express relationships and abstract behaviors. It isn't the only way to achieve polymorphism though. Prototype is another way to express polymorphism that is different from inheritance. JavaScript is an example of a language that uses prototype. I'd imagine there are other ways too.

Gen answered 10/6, 2011 at 15:8 Comment(0)
O
3

Oracle documentation quoted the difference precisely.

inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits. (Note that hiding fields is generally bad programming practice.)

polymorphism: 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.

polymorphism is not applicable for fields.

Related post:

Polymorphism vs Overriding vs Overloading

Obscurantism answered 22/9, 2016 at 11:16 Comment(0)
R
3

Inheritance is a concept related to code reuse. For example if I have a parent class say Animal and it contains certain attributes and methods (for this example say makeNoise() and sleep()) and I create two child classes called Dog and Cat. Since both dogs and cats go to sleep in the same fashion( I would assume) there is no need to add more functionality to the sleep() method in the Dog and Cat subclasses provided by the parent class Animal. However, a Dog barks and a Cat meows so although the Animal class might have a method for making a noise, a dog and a cat make different noises relative to each other and other animals. Thus, there is a need to redefine that behavior for their specific types. Thus the definition of polymorphism. Hope this helps.

Rodrick answered 21/7, 2017 at 16:48 Comment(0)
P
2

Polymorphism is achieved by Inheritance in Java.

├── Animal
└── (instances)
    ├── Cat
    ├── Hamster
    ├── Lion
    └── Moose

├── interface-for-diet
│   ├── Carnivore
│   └── Herbivore
├── interface-for-habitat
│   ├── Pet
│   └── Wild

public class Animal {
    void breath() {
    };
}

public interface Carnivore {
    void loveMeat();
}

public interface Herbivore {
    void loveGreens();
}

public interface Pet {
    void liveInside();
}

public interface Wild {
    void liveOutside();
}

public class Hamster extends Animal implements Herbivore, Pet {

    @Override
    public void liveInside() {
        System.out.println("I live in a cage and my neighbor is a Gerbil");
    }

    @Override
    public void loveGreens() {
        System.out.println("I eat Carrots, Grapes, Tomatoes, and More");
    }
}

public class Cat extends Animal implements Carnivore, Pet {
    @Override
    public void liveInside() {
        System.out.println("I live in a cage and my neighbr is a Gerbil");
    }

    @Override
    public void loveMeat() {
        System.out.println("I eat Tuna, Chicken, and More");
    }
}

public class Moose extends Animal implements Herbivore, Wild {

    @Override
    public void liveOutside() {
        System.out.println("I live in the forest");
    }

    @Override
    public void loveGreens() {
        System.out.println("I eat grass");
    }
}

public class Lion extends Animal implements Carnivore, Wild {

    @Override
    public void liveOutside() {
        System.out.println("I live in the forest");
    }

    @Override
    public void loveMeat() {
        System.out.println("I eat Moose");
    }
}

Hamster class inherits structure from Animal, Herbivore and Pet to exhibit Polymorphic behaviorism of a domestic pet.

Cat class inherits structure from Animal, Carnivore and Pet to also exhibit Polymorphic behaviorism of a domestic pet.

Pincenez answered 30/1, 2018 at 16:32 Comment(0)
W
1

Polymorphism is an effect of inheritance. It can only happen in classes that extend one another. It allows you to call methods of a class without knowing the exact type of the class. Also, polymorphism does happen at run time.

For example, Java polymorphism example:

enter image description here

Inheritance lets derived classes share interfaces and code of their base classes. It happens at compile time.

For example, All Classes in the Java Platform are Descendants of Object (image courtesy Oracle):

enter image description here

To learn more about Java inheritance and Java polymorphism

Walrath answered 12/4, 2019 at 17:0 Comment(0)
P
1

Inheritance leads to polymorphism, and as such both cannot be compared together like would you compare Car and its AC.

If the question is Define Inheritance and Polymorphism in simple terms, then the definitions as picked from Java docs are:

Inheritance : Object-oriented programming allows classes to inherit commonly used state and behaviour from other classes.

Polymorphism : Subclasses of a class can define their own unique behaviours and yet share some of the same functionality of the parent class.

Pumphrey answered 3/9, 2021 at 7:50 Comment(0)
O
0

The main purpose of polymorphism : To create reference variable to super class and holding the subclass object => an object can perform multiple behaviours.

In inheritance, subclass inherit the properties of super class.

Orator answered 23/10, 2011 at 7:29 Comment(0)
H
0

If you use JAVA it's as simple as this:

Polymorphism is using inherited methods but "Overriding" them to do something different (or the same if you call super so wouldn't technically be polymorphic).

Correct me if I'm wrong.

Histrionism answered 6/1, 2015 at 0:3 Comment(0)
J
0

inheritance is kind of polymorphism, Exactly in fact inheritance is the dynamic polymorphism. So, when you remove inheritance you can not override anymore.

Jaramillo answered 7/12, 2017 at 15:58 Comment(0)
E
0

With Inheritance the implementation is defined in the superclass -- so the behavior is inherited.

class Animal
{
  double location;
  void move(double newLocation)
  {
    location = newLocation;
  }
}

class Dog extends Animal;

With Polymorphism the implementation is defined in the subclass -- so only the interface is inherited.

interface Animal
{
  void move(double newLocation);
}

class Dog implements Animal
{
  double location;
  void move(double newLocation)
  {
    location = newLocation;
  }
}
Eckhardt answered 11/9, 2019 at 15:24 Comment(1)
Regarding inheritance, I would appreciate it if you can add "... the behaviour is inherited (assuming we don't override anything in the subclass)".Bioscopy
Y
-1

Inheritance is when class A inherits all nonstatic protected/public methods/fields from all its parents till Object.

Yovonnda answered 10/6, 2011 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.