Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

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:
Java
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?
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900