Polymorphism


Polymorphism

Polymorphism is one of the four pillars of oops and means to take more than one form. An ability to create multiple functions with the same name. Polymorphism can help us to create consistent code.

Example:

public interface Food{}
public class Fruit{}
public class Mango extends Fruit implements Food {}

Polymorphism is mainly divided into two types:

  • Compile time Polymorphism
  • Runtime Polymorphism

Compile-time polymorphism or static polymorphism:

It can be obtained by function overloading or operator overloading. Method Overloading: An ability to create multiple functions with the same name but different parameters. Functions can be overloaded by modifying the number of arguments or/and modifying the type of arguments.

Runtime polymorphism or Dynamic Method Dispatch:

A function calls to the overridden method at run time can be resolved. It can be obtained by Method Overriding.
Method overriding happens when a derived class has a definition for one of the member functions of the base class.

Example No.1:

Com.knowledge2life class Website { void run(){System.out.println("Knowledge2life1");} } class Website1 extends Website{ void run(){System.out.println("Programming Knowledge2life");} public static void main(String args[]){ Website1 obj = new Website1(); obj.run(); } }

OUTPUT:

Programming Knowledge2life

Example No.2:

Com.knowledge2life class Website { public void example1() { System.out.println("Knowledge2life1"); } } class poly1 extends Website { public void example1() { System.out.println("Knowledge2life2"); } } class poly2 extends Website { public void example1() { System.out.println("Knowledge2life3"); } } public class Main { public static void main(String[] args) { Website web1 = new Website(); Website web2 = new poly1(); Website web3 = new poly2(); web1.example1(); web2.example1(); web3.example1(); } }

OUTPUT:

Knowledge2life1
Knowledge2life2
Knowledge2life3