Runt time polymorphism
Run time polymorphism or dynamic polymorphism- This polymorphism is used to happen at run time.
- The best example of run time polymorphism is method overriding.
Method overriding
- In a super and sub classes method having same name and same type of parameters or arguments.
- In overriding, reference of super class can hold the super class object or an object of any sub classes of super class.
- Example: Suppose class A is super class, class B is sub class of A, reference of A class can hold the A class object or an object of B class.
- A a1 = new A(); // valid statement
- A a2 = new B(); // valid statement
- In overriding at compile time compiler dont have any idea about which method will execute, only JVM will decide as which method will execute at run time.
Rules for overriding
- Without inheritance there is no concept of overriding, simply i can say if there is no inheritance concept then please dont waste your time by speaking about overriding concept
- Overriding concept belongs to inherited methods.
- Overriding concept is not applicable for constructors.
- In overriding methods may have different type of return types.
- If we are speaking about abstract methods then overriding concept will involve here also.
- Overriding concept is not applicable for final methods, we will get compile time error while overriding final methods.
- Overriding concept is not applicable for static methods, we will not get compile time error while overriding static methods but its not overriding it is method hiding.
- Another name for overriding is run time polymorphism.
---------------------------------------------------------------------------------------------------
Program : Overriding example
Output :
class A
{
public void method1()
{
System.out.println(“method1 from super class A”);
}
}
class B extends A
{
}
class B extends A
{
public void method1()
{
System.out.println(“method1 from sub class B”);
}
}
class Overriding1
{
public static void main(String args[])
{
A a1 = new A();
a1.method1();
B b1 = new B();
b1.method1();
a1.method1();
B b1 = new B();
b1.method1();
}
}
Compile : javac Overriding1.java
Run : java Overriding1
Output :
---------------------------------------------------------------------------------------------------
Thanks for your time.
Nireekshan