Polymorphism

1. Overview

Polymorphism refers to different behavior of an object for same method name in Object Oriented Programming.
Every child class can have different unique behavior for the method it extends from the Parent class or more than one method with same name with different arguments behave differently.

All child class has its own unique behavior, even though it extends a behavior from the same Parent class.

There are 2 different types of Polymorphism in Java.

  • Runtime Polymorphism
  • CompileTime Polymorphism

As it name indicates, method behavior will be visible to us during Runtime/Compile time.

1.1. Runtime Polymorphism

This is also called as Method Overriding., where base class method is overriden by the child classes, and child class implement their own functionality.

In the above example, Pet is a base class, which has the behaviour makeSound(), just prints Sound.
The makeSound() method in Hen & Cat classes are different, but override the default Pet Sound and not applicable to other.

makeSound() method achieves Polymorphism since Hen & Cat overrides and made their own behaviour for the same call.

In the above
pet, catPet and henPet are all the same Class Object, but the extended Class behave in their own way., which is a polymorphism behavior.

JVM invokes the actual child class methods or behaviors even though child objects takes the parent class form.

This is called Runtime Polymorphism., where these behaviors are happening during runtime.

Result:

1.2. Compile-time Polymorphism

This is also called as Method Overloading., where a class has multiple methods with same names, with different arguments.

Methods are overloaded by using different arguments., and same method name. Return type can be either same or different.

In the above class, add() method is overloaded with additional argument (integer z), and also with a different datatype argument(double y).

However during compile time, the compiler will identify whether the method is overloaded, if any, compiler will throw a compiler error.

Result

You may also like...

1 Response

  1. Chaitany says:

    Thanks, This is a good post of Polymorphism, which helped me a lot.,

Leave a Reply

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