Sunday 23 October 2016

Run time

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
  1. 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
  2. Overriding concept belongs to inherited methods.
  3. Overriding concept is not applicable for constructors.
  4. In overriding methods may have different type of return types.
  5. If we are speaking about abstract methods then overriding concept will involve here also.
  6. Overriding concept is not applicable for final methods, we will get compile time error while overriding final methods.
  7. 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.
  8. Another name for overriding is run time polymorphism.
---------------------------------------------------------------------------------------------------
Program           :       Overriding example
Program name  :       Overriding1.java
Output             :      
      method1 from super class A
      method1 from sub class B

class A
{
        public void method1()
        {
                System.out.println(“method1 from super class 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();  
        }
}

Compile           :       javac Overriding1.java
Run                 :       java Overriding1
Output             :      
     method1 from super class A
     method1 from sub class B     
---------------------------------------------------------------------------------------------------
Thanks for your time.
Nireekshan