Java Reference
In-Depth Information
References of interface type, however, can be used only to access mem-
bers of that interface. For example, the following will produce a compile-
time error:
Comparable<Point> obj = new Point();
double dist = obj.distance(p1); // INVALID: Comparable has
// no distance method
If you want to treat
obj
as a
Point
object you must explicitly cast it to
that type.
You can invoke any of the
Object
methods using a reference of an inter-
face type because no matter what interfaces the object implements, it is
always an
Object
and so has those methods. In fact, any interface that
does not extend some other interface implicitly has members matching
each of the public methods of
Object
(unless the interface explicitly over-
rides them). Hence, the following is legal:
String desc = obj.toString();
as is assigning an interface reference to an
Object
reference.