Runtime Polymorphism JAVA - Polymorphism - UCS - Unleash-Coding-Skills

Sunday, 3 June 2018

Runtime Polymorphism JAVA - Polymorphism - UCS


I think you have learned what is a polymorphism, type of polymorphism and Compile time polymorphism in the before post if not go through this link and continue this for more detailed understanding.

https://www.unleashcodingskills.com/2018/06/polymorphism-in-java-compile-and.html

You can have a method in a subclass overrides the method in its super class with the same name and signature.Java virtual machine (JVM)   determines the proper method to call at the runtime, not at the compile time.

What is Method Overriding?
Methods having same signature and name in both parent class and the derived class. And the method in the derived class is called overridden method.

The following example shows the runtime polymorphism.

import java.io.*;
 class A
{
    void test1()
    {
        System.out.println("Inside Parent Class test1");
    }
}

 class B extends A
{
    void test1()
    {
        System.out.println("inside child class test1");
    }
}
public class C 
{
    public static void main(String args[])
    {
     B obj1 = new B();
     A obj2 = new A();
     obj1.test1();   
     obj2.test1();
    }
}

In this example, We can see class A and Class B that extended class A.
In both the class there a method test1().

From this, it is clearly evident that class A's method test1() is overridded in Class B.

The output of the above code is:
Inside child class test1
Inside Parent class test1

Here  we can observe that we can also access the parent class test1() by creating its instance like
A obj2 = new A();
Inside Parent class test1

To access the test1()  in derived class we must create the instance for that in the derived class as
B obj1 = new B();
So the output for this obj1.test1(); is
Inside child class test1.

Happy Coding..............


No comments:

Post a comment