8.3.3
Examples of Field Declarations
CLASSES
class Point {
int x = 2;
}
class Test extends Point {
double x = 4.7;
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);
}
}
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
implemented
by instances of class
Test
. In other words,
every instance of class
Test
contains two fields, one of type
int
and one of type
float
. Both fields bear the name
x
, but within 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 variable
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
float
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();
152
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved