Java Polymorphism:

  • Polymorphism is the ability to take on many forms of a object.
  • The most common use of java polymorphism occurs when the context of a parent group is used in reference to an object of a child class.

 

Real life example of polymorphism:

  • Suppose that if you are in the classroom room then at that time you behave like a student, when you are in the market at that time, then you behave like a customer, when you have a son in your house or Treats like a daughter, there is a person present here with different behaviors.

 

Two types of polymorphism in Java:

  • Method overloading (compile-time polymorphism)
  • Method overriding (run-time polymorphism)

 

Method Overloading:

  • If a class has several methods from the same name but there are different arguments, it is known as the method overloading.
  • The method is to define two or more methods of the same name in the overloading class, provided that the logic list or parameters are different.
  • This increases the readability of the program.

 

Example:

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.

Output:

 

Method Overriding: 

  • If the basic method of subclass (child class) is declared in the same method, it is known as method override in Java.
  • The child class has the same method as the base class. In such cases, the child class overrides the basic class system without touching the source code of the base class.
  • In this process, an override method is called through the reference variable of the super class.
  • The reference to determining the method to be called is based on the object outlined by the reference variable.
  • Law override applies only to inherited methods.
  • The overriding method may have different return types.
  • Static and final methods can not be overridden.
  • Constructors can not be overridden

 

Example:

Output:

 

Difference between method overloading and method overriding in java Polymorphism:

 

Method OverloadingMethod Overriding
1. Method overloading is used to increase the readability of the program.1. The method is used to provide specific implementation of the overwritten method, which is already provided by its Superclass.
2. The method is done within the overloading class.2. The method overriding occurs in two classes, with IS-A (inheritance) relationships.
3. In case of method overload, the parameter should be different.3. In case of override method, the parameter should be similar.
4. Method overloading is an example of compile time polymorphism.4. An example of run time polymorphism.