Java Reference
In-Depth Information
}
void printX() {
System.out.println(x + " " + super.x);
}
}
This program produces the output:
4.7 2
because the declaration of x in class Test hides the definition of x in class Point , so class
Test does not inherit the field x from its superclass Point . Within the declaration of class
Test , the simple name x refers to the field declared within class Test . Code in class Test
may refer to the field x of class Point as super.x (or, because x is static , as Point.x ). If the
declaration of Test.x is deleted:
Click here to view code image
class Point {
static int x = 2;
}
class Test extends Point {
public static void main(String[] args) {
new Test().printX();
}
void printX() {
System.out.println(x + " " + super.x);
}
}
then the field x of class Point is no longer hidden within class Test ; instead, the simple
name x now refers to the field Point.x . Code in class Test may still refer to that same
field as super.x . Therefore, the output from this variant program is:
2 2
Example 8.3.1.1-3. Hiding of Instance Variables
Click here to view code image
class Point {
int x = 2;
}
class Test extends Point {
double x = 4.7;
void printBoth() {
System.out.println(x + " " + super.x);
Search WWH ::




Custom Search