Java Reference
In-Depth Information
This program produces the output:
Click here to view code image
t.x=1 when t holds a class T at run time.
s.x=0 when s holds a class S at run time.
s.x=0 when s holds a class T at run time.
The last line shows that, indeed, the field that is accessed does not depend on the run-
time class of the referenced object; even if s holds a reference to an object of class T ,
the expression s.x refers to the x field of class S , because the type of the expression
s is S . Objects of class T contain two fields named x , one for class T and one for its
superclass S .
This lack of dynamic lookup for field accesses allows programs to be run efficiently
with straightforward implementations. The power of late binding and overriding is
available, but only when instance methods are used. Consider the same example using
instance methods to access the fields:
Click here to view code image
class S { int x = 0; int z() { return x; } }
class T extends S { int x = 1; int z() { return x; } }
class Test2 {
public static void main(String[] args) {
T t = new T();
System.out.println("t.z()=" + t.z() + when("t", t));
S s = new S();
System.out.println("s.z()=" + s.z() + when("s", s));
s = t;
System.out.println("s.z()=" + s.z() + when("s", s));
}
static String when(String name, Object t) {
return " when " + name + " holds a "
+ t.getClass() + " at run time.";
}
}
Now the output is:
Click here to view code image
t.z()=1 when t holds a class T at run time.
s.z()=0 when s holds a class S at run time.
s.z()=1 when s holds a class T at run time.
The last line shows that, indeed, the method that is accessed does depend on the run-
time class of the referenced object; when s holds a reference to an object of class T ,
Search WWH ::




Custom Search