Tuesday, November 18, 2008

Reference variable vs. Real object

This example shows what happens for the instance method, static method, variable in the inheritance.

======================== Code ========================
public class Sub extends Super{

int x = 15;
static int y = 25;
public static void main(String args[]){

//super reference and super object
Super t = new Super();
out.println(t.x + " " + t.y);
t.methodOne();
t.methodTwo();

//super reference and sub object
Super ts = new Sub ();
out.println(ts.x + " " + ts.y);
ts.methodOne();
ts.methodTwo();

//sub reference and sub object
Sub s = new Sub();
out.println(s.x + " " + s.y);
s.methodOne();
s.methodTwo();
}
static void methodOne() {out.println("Sub methodOne()");}
void methodTwo() {
out.println("Sub methodTwo()");
methodOne();
}
}

class Super{
int x = 10;
static int y = 20;
static void methodOne() {out.println("Super methodOne()");}
void methodTwo() {
out.println("Super methodTwo()");
methodOne();
}
}
================================================

======================== Answer ========================
10 20
A methodOne()
A methodTwo()
A methodOne()
10 20
A methodOne()
B methodTwo()
B methodOne()
15 25
B methodOne()
B methodTwo()
B methodOne()
================================================

======================== Conclusion ========================
static methods and variables are based on the reference type
Real object type determines which overridden method is used at runtime
================================================

No comments: