THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

you can do


System.out.println("Z.val=" + Z.val + ", Z.sum=" + Z.sum);


but there is no way to refer to X.val via Z. However, given an instance of Z you can use an explicit cast to
access X.val:


Z z = new Z();
System.out.println("z.val=" + z.val +
", ((Y)z).val=" + ((Y)z).val +
", ((X)z).val=" + ((X)z).val);


which prints out


z.val=2, ((Y)z).val=2, ((X)z).val=1


as you would expect. Again these are the same rules that apply to static fields in extended classesit doesn't
matter whether a class inherits a static field from a superclass or a superinterface.


While all these rules are necessary from a language perspective, they have little practical consequencethere
are few reasons to hide existing fields, and all accesses to static fields, whether class or interface, should be
via the name of the type in which that field is declared.


If an interface inherits two or more constants with the same name, then any simple reference to the constant is
ambiguous and results in a compile-time error. For example, given the previous interface declarations and the
following:


interface C {
String val = "Interface C";
}
interface D extends X, C { }


then the expression D.val is ambiguousdoes it mean the integer val or the String reference val? Inside
D you would have to explicitly use X.val or C.val.


A class that implements more than one interface, or that extends a class and implements one or more
interfaces, can experience the same hiding and ambiguity issues as an interface that extends more than one
interface. The class's own static fields can hide the inherited fields of the interfaces it implements or the class
it extends, and simple references to multiply-inherited non-hidden fields will be ambiguous.


4.3.2. Inheriting, Overriding, and Overloading Methods


A subinterface inherits all the methods declared in its superinterfaces. If a declared method in a subinterface
has the same signature (name and parameter list) as an inherited method and the same, or covariant, return
type, then the new declaration overrides any and all existing declarations. Overriding in interfaces, unlike
overriding in classes, has no semantic effectthe interface effectively contains multiple declarations of the same
method, but in any one implementing class there can only be one implementation of that method.

Free download pdf