Friday 9 October 2015

Understand the Compile time and Run time polymorphism

Compile time and Run time polymorphism in deep

The output of below program should be “Inside child: int” because we are creating the calling the method on the Child class instance.

Its wrong assumption, method() is overloaded in child class not override and overloading support for the compile time polymorphism. At the compile time, the method parent class will bind as we are using the Parent class reference.

class Super {
      void method(double num) {
            System.out.println("Inside parent: double");
      }
}

class Sub extends Super {
      void method(int num) {
            System.out.println("Inside child: int");
      }
}

public class PolymorphismTest {
      public static void main(String[] args) {
            Super object = new Sub();
            object.method(5);
      }
}
Output:
      Inside parent: double

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...