10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

EXPRESSIONS Field Access Using a Primary 15.11.1<br />

static String when(String name, Object t) {<br />

return " when " + name + " holds a "<br />

+ t.getClass() + " at run time.";<br />

}<br />

}<br />

produces the output:<br />

t.x=1 when t holds a class T at run time.<br />

s.x=0 when s holds a class S at run time.<br />

s.x=0 when s holds a class T at run time.<br />

<strong>The</strong> last line shows that, indeed, the field that is accessed does not depend on the<br />

run-time class of the referenced object; even if s holds a reference to an object of<br />

class T, the expression s.x refers to the x field of class S, because the type of the<br />

expression s is S. Objects of class T contain two fields named x, one for class T<br />

and one for its superclass S.<br />

This lack of dynamic lookup for field accesses allows programs to be run efficiently<br />

with straightforward implementations. <strong>The</strong> power of late binding and overriding<br />

is available, but only when instance methods are used. Consider the same<br />

example using instance methods to access the fields:<br />

class S { int x = 0; int z() { return x; } }<br />

class T extends S { int x = 1; int z() { return x; } }<br />

class Test {<br />

public static void main(String[] args) {<br />

T t = new T();<br />

System.out.println("t.z()=" + t.z() + when("t", t));<br />

S s = new S();<br />

System.out.println("s.z()=" + s.z() + when("s", s));<br />

s = t;<br />

System.out.println("s.z()=" + s.z() + when("s", s));<br />

}<br />

static String when(String name, Object t) {<br />

return " when " + name + " holds a "<br />

+ t.getClass() + " at run time.";<br />

}<br />

}<br />

Now the output is:<br />

t.z()=1 when t holds a class T at run time.<br />

s.z()=0 when s holds a class S at run time.<br />

s.z()=1 when s holds a class T at run time.<br />

<strong>The</strong> last line shows that, indeed, the method that is accessed does depend on the<br />

run-time class of referenced object; when s holds a reference to an object of class<br />

DRAFT<br />

437

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!