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.

CLASSES Examples of Field Declarations 8.3.3<br />

instance methods of class Test may refer to the instance variable x of class Point<br />

as super.x.<br />

Code that uses a field access expression to access field x will access the field<br />

named x in the class indicated by the type of reference expression. Thus, the<br />

expression sample.x accesses a double value, the instance variable declared in<br />

class Test, because the type of the variable sample is Test, but the expression<br />

((Point)sample).x accesses an int value, the instance variable declared in<br />

class Point, because of the cast to type Point.<br />

If the declaration of x is deleted from class Test, as in the program:<br />

class Point {<br />

static int x = 2;<br />

}<br />

class Test extends Point {<br />

void printBoth() {<br />

System.out.println(x + " " + super.x);<br />

}<br />

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

Test sample = new Test();<br />

sample.printBoth();<br />

System.out.println(sample.x + " " +<br />

((Point)sample).x);<br />

}<br />

}<br />

then the field x of class Point is no longer hidden within class Test. Within<br />

instance methods in the declaration of class Test, the simple name x now refers to<br />

the field declared within class Point. Code in class Test may still refer to that<br />

same field as super.x. <strong>The</strong> expression sample.x still refers to the field x within<br />

type Test, but that field is now an inherited field, and so refers to the field x<br />

declared in class Point. <strong>The</strong> output from this variant program is:<br />

2 2<br />

2 2<br />

DRAFT<br />

8.3.3.3 Example: Multiply Inherited Fields<br />

A class may inherit two or more fields with the same name, either from two interfaces<br />

or from its superclass and an interface. A compile-time error occurs on any<br />

attempt to refer to any ambiguously inherited field by its simple name. A qualified<br />

name or a field access expression that contains the keyword super (§15.11.2) may<br />

be used to access such fields unambiguously. In the example:<br />

interface Frob { float v = 2.0f; }<br />

class SuperTest { int v = 3; }<br />

207

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

Saved successfully!

Ooh no, something went wrong!