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: , , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Blogroll

Friends

General

Feeds

 

September 2008
M T W T F S S
« Dec   Nov »
1234567
891011121314
15161718192021
22232425262728
2930  

Recent Posts

Firefox 3