[145] in java-interest

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

Re: Question about casting from classes to interfaces

daemon@ATHENA.MIT.EDU (Arthur van Hoff)
Mon May 29 21:56:37 1995

From: Arthur.Vanhoff@Eng.Sun.COM (Arthur van Hoff)
Date: Mon, 29 May 1995 18:45:39 -0800 (PDT)
To: java-interest@java.Eng.Sun.COM

Hi Jeremy,

> 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.  

If static analysis of the code does not conclude that the cast is
impossible, then you have to allow it and insert a runtime check.
When casting an interface to a class, a class to an interface or
an interface to an interface it is in general impossible to know
for sure that the cast is impossible. 

> I presume a subclass of DisplayItem
> could implement Alignable, which is how the code ever gets run.

Exactly!

> 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?

The are always allowed, but they usually result in a runtime check!

Have fun,

	Arthur van Hoff (avh@eng.sun.com)
	http://java.sun.com/people/avh/
	Sun Microsystems Inc, M/S UPAL02-301,
	100 Hamilton Avenue, Palo Alto CA 94301, USA
	Tel: +1 415 473 7242, Fax: +1 415 473 7104

-
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