CLASSES
Examples of Field Declarations
8.3.3
sample.printBoth();
System.out.println(sample.x + " " +
((Point)sample).x);
}
}
then the field
x
of class
Point
is no longer hidden within class
Test
. Within
instance methods in the declaration of class
Test
, the simple name
x
now refers to
the field declared within class
Point
. Code in class
Test
may still refer to that
same field as
super.x
. The expression
sample.x
still refers to the field
x
within
type
Test
, but that field is now an inherited field, and so refers to the field
x
declared in class
Point
. The output from this variant program is:
2 2
2 2
8.3.3.3
Example: Multiply Inherited Fields
A class may inherit two or more fields with the same name, either from two inter
faces or from its superclass and an interface. A compile time error occurs on any
attempt to refer to any ambiguously inherited field by its simple name. A qualified
name or a field access expression that contains the keyword
super
( 15.10.2) may
be used to access such fields unambiguously. In the example:
interface Frob { float v = 2.0f; }
class SuperTest { int v = 3; }
class Test extends SuperTest implements Frob {
public static void main(String[] args) {
new Test().printV();
}
void printV() { System.out.println(v); }
}
the class
Test
inherits two fields named
v
, one from its superclass
SuperTest
and
one from its superinterface
Frob
. This in itself is permitted, but a compile time
error occurs because of the use of the simple name
v
in method
printV
: it cannot
be determined which
v
is intended.
The following variation uses the field access expression
super.v
to refer to
the field named
v
declared in class
SuperTest
and uses the qualified name
Frob.v
to refer to the field named
v
declared in interface
Frob
:
interface Frob { float v = 2.0f; }
class SuperTest { int v = 3; }
class Test extends SuperTest implements Frob {
public static void main(String[] args) {
new Test().printV();
153
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