Method overriding is one of the good examples of Runtime Ploymorphism in Java. With method overriding methods are bound to object instances during runtime which is best explained by the Java Sample Code below
package com.javainterviewquestion.
public class RuntimePolymorphismCheck extends BaseClass{ public void test() { System.out.println(" In the test Method for Child Class"); } public static void main(String args[]) { BaseClass childClass = new RuntimePolymorphismCheck(); childClass.test(); }
}
class BaseClass { public BaseClass() { test(); } public void test() { System.out.println(" In the test Method for Base Class"); } }
This question stumps quite a few people but the output of the above code is
In the test Method for Child Class
or
In the test Method for Child Class In the test Method for Base Class
But the actual output of the above code is
In the test Method for Child Class In the test Method for Child Class
as Java decides at runtime as to what class should the object bind to.
No comments:
Post a Comment