udeleng
udeleng

Reputation: 157

Java Explicit Reference Casting

How come there is no compiler error casting Number to List? I thought the types had to be relate.

Number k = 10;
List m = new ArrayList();
m = (List)k;

Upvotes: 8

Views: 599

Answers (1)

Bala R
Bala R

Reputation: 108947

Just a guess but I think it's got something to do with m being an interface reference. If you change it to ArrayList m = new ArrayList();, it shows a compile time error.

I thought the types had to be relate.

Number is a class(abstract) and List is an interface so they can be related through another class.

so technically you could have

class Foo extends Number implements List
{
   ... 
}

and

    Number k = ... ; // 
    List m = new Foo();
    m = (List) k;

could be legal and will run without exception if k is pointing to a type compatible with Foo.

So if you refer to an object by an interface, resolution is deferred till runtime.

Upvotes: 9

Related Questions