import java.util.Collection;


public class Test
{
    public static void main(String[] args)
    {
        Collection c = null;
        Test s = null;

        s = (Test) c;
    }
}

在上面的代码示例中,我铸造集合对象的测试对象。 (忽略空指针)。测试有应用于任何集合,但这一计划没有的关系将通过所有的编译时检查。

我不知道这是为什么。我的假设是,接口被忽略,因为它们太复杂。他们没有共同的超类型,每一类可以实现多个接口,所以类/接口层次结构太复杂,以有效地搜索?

除了这个原因,我虽然难住了。有谁知道?!

有帮助吗?

解决方案

“非最后的”是这里的关键字。你可以具有另一种类

public class Test2 extends Test implements Collection

,其实例将最终被分配给s制造铸造完全合法的。

其他提示

由于Test的子类可以潜在地Collection的一个子类型,以及!语言规范被设计为有点柔性的,以允许可以在运行时被验证的类型转换。

我们可以从不同的透视图它:任何非最终类可浇铸任何接口

import java.util.function.Predicate;

public class Test {
    public static void main(String[] args) {
        Predicate check;

        try {
            /*It's ok to cast to ANY interface because the Base class is not final.
              Java compiler allows it because some class may extend it 
              and implement the predicate interface. 
              So java compiler can check it only at runtime time not compile time.             
            */
            check = (Predicate)(new Base());

            /*
             Java compiler doesn’t allow it because the BaseFinal is final.
             And it means that no one can extend it and implement interface Predicate. 
             So java compiler can check it at compile time.
            */
            //check = (Predicate)(new BaseFinal()); 
        } catch (ClassCastException e) {
            System.out.println("Class Cast Exception");
        }
        check = (Predicate)(Base)(new Child());
    }    
}
final class BaseFinal {};

class Base {}

class Child extends Base implements Predicate {
    public boolean test(Object t) { return true; }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top