Thursday, September 03, 2009

Accessing super-super class variables

In core java, Sub-classes can use super keyword to access the shadowed variables in super-classes. This technique allows for accessing only the immediate super-class. super.super is not valid. But casting the 'this' reference to classes up above the hierarchy will do the trick. By this way, variables in super-classes above any level can be accessed from a sub-class, since variables are resolved at compile time, when we cast the 'this' reference to a super-super-class, the compiler binds the super-super-class variable. But this technique is not possible with methods since methods are resolved always at runtime, and the method gets called depends on the type of object, not the type of reference variable. So it is not at all possible to access a method in a super-super-class from a subclass.

Example:
class A{
int c=1;
public void disp(){
System.out.println("A");
}
}

class B extends A{
int c=2;
public void disp(){
System.out.println("B");
}
}

class C extends B{
int c=3;
public void disp(){
System.out.println("C");
}

void demo(){
disp();
super.disp();
((A)this).disp();
System.out.println(c);
System.out.println(super.c);
System.out.println(((A)(this)).c);
}
}
public class G{
public static void main(String args[]){
new C().demo();
}
}

Output:-
C
B
C
3
2
1

No comments:

Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory