Java Reference
In-Depth Information
}
public static void main(String[] args) {
Test sample = new Test();
sample.printBoth();
System.out.println(sample.x + " " + ((Point)sample).x);
}
}
This program produces the output:
4.7 2
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
. It must be noted, however, that
while the field
x
of class
Point
is not inherited by class
Test
, it is nevertheless
imple-
mented
by instances of class
Test
. In other words, every instance of class
Test
contains
two fields, one of type
int
and one of type
double
. Both fields bear the name
x
, but with-
in the declaration of class
Test
, the simple name
x
always refers to the field declared
within class
Test
. Code in instance methods of class
Test
may refer to the instance vari-
able
x
of class
Point
as
super.x
.
Code that uses a field access expression to access field
x
will access the field named
x
in the class indicated by the type of reference expression. Thus, the expression
sample.x
accesses a
double
value, the instance variable declared in class
Test
, because the type of
the variable
sample
is
Test
, but the expression
((Point)sample).x
accesses an
int
value, the
instance variable declared in class
Point
, because of the cast to type
Point
.
If the declaration of
x
is deleted from class
Test
, as in the program:
class Point {
static int x = 2;
}
class Test extends Point {
void printBoth() {
System.out.println(x + " " + super.x);
}
public static void main(String[] args) {
Test sample = new Test();
sample.printBoth();
System.out.println(sample.x + " " + ((Point)sample).x);
}
}