Advertisement

Polymorphism

Polymorphism


Poly means "many" and morphism means "form", so polymorphism mean same situation where something happen/occur in many different form. In Programming it mean the concept that method/classes of different type can use same interface. When we inherit a child class from parent class than there are methods in child class which are also in parent class, then we use the concept of polymorphism  Each type can use its own method/class according to their use. The concept of Polymorphism is one of the basic concepts of object oriented programming.



Polymorphism definition



There are two type of Polymorphism Static and Dynamic. In static polymorphism we assign to compiler before the execution which one to execute and in dynamic we cannot assign before execution compiler decides by itself at the time of execution. The concept of overriding and overloading also came with polymorphism. we learn about these in detail in our upcoming blogs.


For example we have 2 methods in Java with same name.

In the below example we have a class with name Animals which has a method (move), we have also created another class where Dog class also have a move method, other than this Dog class also inherit move method from Animal class.  Now in TestDog (main Class) we use move method with different way according to our requirement.




class Animals { public void move(){ System.out.println("Animals can move by its own"); } } class Dog extends Animals { public void move() { System.out.println("Dogs can walk and run faster"); } } public class TestDog { public static void main(String args[]) { Animals a = new Animals(); Animals b = new Dog(); a.move();//output: Animals can move by its own b.move();//output: Dogs can walk and run faster } }

Post a Comment

0 Comments