Java: Overriding Vs Hiding
September 11, 2008
Here is an interesting piece of code in Java. Say there are two classes, one extending another:
class A {
public static void sampleMethod1() {
System.out.println("In sampleMethod1:A");
}
public void sampleMethod2(){
System.out.println("In sampleMethod2:A");
}
}
class B extends A {
public static void sampleMethod1() {
System.out.println("In sampleMethod1:B");
}
public void sampleMethod2() {
System.out.println("In sampleMethod2:B");
}
}
What is the output of the following:
1. A a = new B();
a.sampleMethod1();
2. B b = new B();
((A)b).sampleMethod1();
3. A a = new B();
a.sampleMethod2();
4. B b = new B();
((A)b).sampleMethod2()
Interestingly, its not possible to invoke a method in the parent which is overridden in the child class, from a child class instance. Its a dependency on the runtime object type. At the same time, you can always invoke a static method hidden in the child class by type casting it or using an object reference of type its parent. Its a static binding at class level.
Entry Filed under: English, technical. Tags: hiding, java, overriding.



Trackback this post | Subscribe to the comments via RSS Feed