开发者

Java Explicit Reference Casting

How come there is no compiler error casting Number to L开发者_如何学编程ist? I thought the types had to be relate.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜