. . .

Explain Polymorphism with suitable examples?

Polymorphism

Polymorphism means the ability to take more than one form of the same property. For example, consider an addition operation. It shows different behavior in different types of data. For two numbers, it will generate a sum. The numbers may integers or float. Thus the addition for integers is different from the addition to floats.

This allows one name to be used for several related but slightly different purposes. The purpose of it is to let one name be used to specify a general class of action. We have already dealt with this type of polymorphism. The other type of polymorphism simplifies, the syntax of performing the same operation. With the hierarchy of classes, the programmer can have multiple methods with the same name but their functionality changes according to the situation.

An example is shown in Figure, where a single function name, i.e. draw can be used to draw different shapes. The name is the same in all the classes but the functionality differs. This is known as function overriding, which is a type of polymorphism. We will discuss it in detail. In our example, we also used a function “area” which was inherited by all the three derived classes, i.e. triangle, circle, and rectangle. But in the cases of the circle and the triangle, we override the function area because the data types and number of parameters varies.

Polymorphism
Figure

Now let us try to understand Polymorphism with a short programming

* polymorphisom samples  */

public class Three{
  String str="Hello";
  void print()
  {
    System.out.println(str);
  }
  void print(String p)
  {
    System.out.println(str+" "+p);
  }
  void print(int r)
  {
    System.out.println(r);
  }
  void print(String p,int r)
  {
    System.out.println(str+" "+p+" Your age is "+r);
  }
}


class ThreeMain{
    public static void main(String args[])
    {
      Three three= new Three();
      three.print();
      three.print("Mayaz");
      three.print(22);
      three.print("Mayaz",28);

    }

}
Please share the article

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × four =