Java – Runtime Polymorphism

Runtime polymorphism:

  • Runtime Polymorphism is a Method overriding technique.
  • Defining a method in the Child class with the same name and same signature of its Parent class.
  • We can implement Method overriding only in Parent-Child (Is-A) relation.
Child object shows the functionality(behavior) of Parent and Child is called Polymorphism
class Parent
{
            void behave(){
                        System.out.println(“Parent behavior”);
            }
}
class Child extends Parent
{
            void behave(){
                        System.out.println(“Child behavior”);
            }
            void behavior(){
                        super.behave();
                        this.behave();
            }
}
class Main
{
            public static void main(String[] args){
                        Child child = new Child();
                        child.behavior();
            }
}

Object Up-casting: We can store the address of Child class into Parent type reference variable.

Using parent address reference variable, we can access the functionality of Child class.
class Parent
{
            void fun(){
                        System.out.println(“Parent’s functionality”);
            }
}
class Child extends Parent
{
            void fun(){
                        System.out.println(“Updated in Child”);
            }
}
class Upcast
{
            public static void main(String[] args)  {
                        Parent addr = new Child();
                        addr.fun();
            }
}

Why it is calling Child functionality in the above application?

  • Hostel address = new Student();
    • address.post();  ->  The Post reaches student
  • Owner address = new Tenant();
    • address.post();  -> The Pose reaches tenant

Down casting: The concept of collecting Child object address back to Child type reference variable from Parent type.

When we use down-casting?

  • Consider a method has to return object without knowing the class name, then it returns the address as Object.
  • For example:
    • Object  getObject();
  • As a programmer we collect the Object and convert into corresponding object type reference variable.
  • For example:
    • Employee obj = (Employee)getObject();
Scroll to Top