Click here to Skip to main content
14,606,383 members
Rate this:
Please Sign up or sign in to vote.
So i am reading head First java book and when its explain inheritance right after that it goes to polymorphism without saying how are they connected what is the benefit its just say its make youe code flexible and others can use your code to be honest its so confusing i know what inheritance is and can't say i understand polymorphism I have tried looking at some YouTube videos and what i understand from polymorphism is you have a superclass and subclasses and you use array to loop through the subclasses to do some functions

What I have tried:

Please explain with simple English word
Posted
Updated 10-Jul-20 5:32am

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Generally, the ability to appear in many forms. In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.


So you can inherit from a base class, and override base class methods. Then even if the base class method is referenced in a base class variable containing an derived class instance, the system calls the derived class method instead of the base.

Suppose you have a base Animal class, and derive Cat and Dog classes from it.
If the base class has a Feed method, you can then override that in both Cat and Dog classes to ensure the right food and quantity is fed to the right animal type: 85g Whiskas for the Cat class, 250g of Pedigree Chum for the dog.

If you then loop through all your Animals you would use an Animal variable and just call Feed:
for (Animal animal : animals) {
    animal.Feed();
}
The system looks at what type is currently in animal and calls the appropriate Cat.Feed or Dog.Feed as necessary. You don't have to concern yourself about what type of Animal it is, the system works it out for you based on the instance being processed at the time.

That is the essence of Polymorphism: the ability to appear in many forms!

Make sense now?
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100