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.

8.3.3 Examples of Field Declarations CLASSES<br />

206<br />

class Test extends Point {<br />

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

new Test().printX();<br />

}<br />

void printX() {<br />

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

}<br />

}<br />

then the field x of class Point is no longer hidden within class Test; instead, the<br />

simple name x now refers to the field Point.x. Code in class Test may still refer<br />

to that same field as super.x. <strong>The</strong>refore, the output from this variant program is:<br />

2 2<br />

8.3.3.2 Example: Hiding of Instance Variables<br />

This example is similar to that in the previous section, but uses instance variables<br />

rather than static variables. <strong>The</strong> code:<br />

class Point {<br />

int x = 2;<br />

}<br />

class Test extends Point {<br />

double x = 4.7;<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 />

produces the output:<br />

4.7 2<br />

4.7 2<br />

because the declaration of x in class Test hides the definition of x in class Point,<br />

so class Test does not inherit the field x from its superclass Point. It must be<br />

noted, however, that while the field x of class Point is not inherited by class<br />

Test, it is nevertheless implemented by instances of class Test. In other words,<br />

every instance of class Test contains two fields, one of type int and one of type<br />

double. Both fields bear the name x, but within the declaration of class Test, the<br />

simple name x always refers to the field declared within class Test. Code in<br />

DRAFT

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

Saved successfully!

Ooh no, something went wrong!