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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

15.11.2 Accessing Superclass Members using super EXPRESSIONS<br />

438<br />

T, the expression s.z() refers to the z method of class T, despite the fact that the<br />

type of the expression s is S. Method z of class T overrides method z of class S.<br />

<strong>The</strong> following example demonstrates that a null reference may be used to<br />

access a class (static) variable without causing an exception:<br />

class Test {<br />

static String mountain = "Chocorua";<br />

static Test favorite(){<br />

System.out.print("Mount ");<br />

return null;<br />

}<br />

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

System.out.println(favorite().mountain);<br />

}<br />

}<br />

It compiles, executes, and prints:<br />

Mount Chocorua<br />

Even though the result of favorite() is null, aNullPointerException is<br />

not thrown. That “Mount ” is printed demonstrates that the Primary expression is<br />

indeed fully evaluated at run time, despite the fact that only its type, not its value,<br />

is used to determine which field to access (because the field mountain is static).<br />

15.11.2 Accessing Superclass Members using super<br />

<strong>The</strong> special forms using the keyword super are valid only in an instance method,<br />

instance initializer or constructor, or in the initializer of an instance variable of a<br />

class; these are exactly the same situations in which the keyword this may be<br />

used (§15.8.3). <strong>The</strong> forms involving super may not be used anywhere in the class<br />

Object, since Object has no superclass; if super appears in class Object, then a<br />

compile-time error results.<br />

Suppose that a field access expression super.name appears within class C,<br />

and the immediate superclass of C is class S. <strong>The</strong>n super.name is treated exactly<br />

as if it had been the expression ((S)this).name; thus, it refers to the field<br />

named name of the current object, but with the current object viewed as an<br />

instance of the superclass. Thus it can access the field named name that is visible<br />

in class S , even if that field is hidden by a declaration of a field named name in<br />

class C.<br />

<strong>The</strong> use of super is demonstrated by the following example:<br />

interface I { int x = 0; }<br />

class T1 implements I { int x = 1; }<br />

class T2 extends T1 { int x = 2; }<br />

class T3 extends T2 {<br />

DRAFT

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

Saved successfully!

Ooh no, something went wrong!