Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways. Let’s understand through below code…
Code 1:
class tata{ void car(){ print(‘brand is TATA’); } } class nexon extends tata{ void car(){ print(‘brand tata, model -> nexon’); } } class tiago extends tata{ void car(){ print(‘brand tata, model -> tiago’); } } void main(){ late var c1; c1=tata(); c1.car(); c1=nexon(); c1.car(); c1=tiago(); c1.car(); } |

superclass called ‘tata’ that has a method called car(). Subclasses of ‘tata’ are tiago,nexon and they also have their own implementation of method car().
Let’s do some coding with polymorphism…
** remember: we will work with run-time polymorphism means we will work with method overriding.
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of Polymorphisms achieved by Method Overriding.
Let’s understand through below code…
Code 2:
class OS{ // default constructor OS(){ print(‘there are many os there in the world!’); } } class linux extends OS{ linux(){ print(‘this is linux os’); } } class windows extends OS{ windows(){ print(‘this windows which powers millions of laptops!’); } } void main(){ /* parent class ‘OS’ every time when we calls child classes we also calls parent class also. */ late var name; name=OS(); // calling child class constrcutor linux name=linux(); // calling child class constrcutor windows name=windows(); } |
