adsense from aus

Sunday, June 1, 2008

Java instance of subclass

class Base{
int x = 2;
int mmethod(){
return x;
}
}

class Subclass extends Base{
int x = 3;
int mmethod(){
return x;
}
}

public class test3{

public static void main(String[] args){
Base b = new Subclass();
System.out.println(b.x);
System.out.println(b.mmethod());
}
}




When you call an instance method, it is the type of the current object - i.e. the Subclass object - that it used to resolve the call. However, when you call a data member, it is the type of the reference - Base in you example - NOT the type of the current object that is used to resolve the call.

So, becuase you have declared the varibla eb as type Base, that classes data members will be called. Because the variable b holds a reference to an object that is of type Superclass, that - the Superclass object, methods will be called.

Hope that helps.

Here is the source code:

download

No comments: