[141] in java-interest

home help back first fref pref prev next nref lref last post

Question about casting from classes to interfaces

daemon@ATHENA.MIT.EDU (Jeremy Fitzhardinge)
Mon May 29 19:08:34 1995

From: jeremy@sour.sw.oz.au (Jeremy Fitzhardinge)
To: java-interest@java.Eng.Sun.COM
Date: Mon, 29 May 1995 19:17:40 +1000 (EST)

In browser/WRFormatter.java there is the following code:
147 protected void adjustItem(DisplayItem di, int x) {
148	if (di instanceof Alignable) {
149         Alignable	a = (Alignable) di;

My compiler complains:
classsrc/browser/WRFormatter.java:149: error: Can't cast from DisplayItem to Alignable*
but javac doesn't.

Alignable is an interface, and DisplayItem is a class.  DisplayItem
doesn't implement Alignable, and nor does its super, so there's
no obvious reason to assume that they can be connected.  Of course
the "instanceof" ensures that there is a connection, but static
analysis doesn't show it.  I presume a subclass of DisplayItem
could implement Alignable, which is how the code ever gets run.

The spec says that bad casts between classes have to be reported
at compile time, and I'd assumed the same applied to interface
casts.  This is an example where that wouldn't work, so I suppose
that, rather than forcing a cast through Object, interface casts
have looser rules.  In fact, are there any compile-time rules which
can be applied to casting interfaces, or are they always allowed?

	J

-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post