Array Casting

I read a book which stated the following:

Newtype nt;

Oldtype ot;

nt=(Newtype)ot;

Case1: (Result = Always compile OK)

- Newtype is a non-final class and

- Oldtype is an interface

Case2: (Result = Compiler error)

- Newtype is an array and

- Oldtype is an interface

Can someone explain why Case1 is OK but Case is not? Thanks in advance.

[412 byte] By [lamkf1] at [2007-9-26 4:12:56]
# 1

In Case 1, the reference ot could possibly point to an that's an instance of a class that extends Newtype (because it is non-final) and implements OldType. That's why the code compiles -- because it is possible for the cast to not throw ClassCastException.

In Case 2, the code will compile if the interface is java.io.Serializable or java.lang.Cloneable, but will fail otherwise. The reason, of course, is that arrays implement those two interfaces and no others. The cast will always throw ClassCastException if the interface is not one of those two.

schapel at 2007-6-29 13:19:12 > top of Java-index,Archived Forums,Java Programming...
# 2

> I read a book which stated the following:

>

> Newtype nt;

> Oldtype ot;

> nt=(Newtype)ot;

>

> Case1: (Result = Always compile OK)

> - Newtype is a non-final class and

> - Oldtype is an interface

>

> Case2: (Result = Compiler error)

> - Newtype is an array and

> - Oldtype is an interface

>

> Can someone explain why Case1 is OK but Case is not?

> Thanks in advance.

I guess you mean that BOTH conditions MUST be true. In that case:

Case 1:

Since newtype is not final, you don't know at "compile time" what interfaces are implemented on any of its subclasses. As a result, you can not be sure that none of its subclasses implemented the Oldtype interface.

As a result when you see a reference of type Oldtype, you can not be sure at "compile time" if it contains an object which may be a subclass of Newtype or not.

Case 2:

Because an array is not ever an interface and an interface is never an array, their reference types can never hold the same objects. period.

dnoyeB at 2007-6-29 13:19:12 > top of Java-index,Archived Forums,Java Programming...
# 3
and what schapel said too...
dnoyeB at 2007-6-29 13:19:12 > top of Java-index,Archived Forums,Java Programming...