Java Reference
In-Depth Information
a field access expression that contains the keyword super (ยง 15.11.2 ) may be used to
access such fields unambiguously. In the program:
Click here to view code image
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 oc-
curs 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 :
Click here to view code image
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((super.v + Frob.v)/2);
}
}
It compiles and prints:
2.5
Even if two distinct inherited fields have the same type, the same value, and are both
final , any reference to either field by simple name is considered ambiguous and results
in a compile-time error. In the program:
Click here to view code image
interface Color { int RED=0, GREEN=1, BLUE=2; }
interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; }
Search WWH ::




Custom Search