CLASSES
Examples of Field Declarations
8.3.3
8.3.3.1
Example: Hiding of Class Variables
The example:
class Point {
static int x = 2;
}
class Test extends Point {
static double x = 4.7;
public static void main(String[] args) {
new Test().printX();
}
void printX() {
System.out.println(x + " " + super.x);
}
}
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:
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
8.3.3.2
Example: Hiding of Instance Variables
This example is similar to that in the previous section, but uses instance variables
rather than static variables. The code:
151
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