This question already has answers here:
Java: Casting a class to an unrelated interface
                                
                                    (1个答案)
                                
                        
                        
                            Casting between Interfaces and Classes
                                
                                    (2个答案)
                                
                        
                        
                            Why does it compile when casting to an unrelated interface?
                                
                                    (3个答案)
                                
                        
                                2年前关闭。
            
                    
我对这个(适当的)简单的转换示例有一个尴尬的问题。请你帮助我好吗?

public class Example1 {

interface ParentIf{}
interface ChildIf extends ParentIf {}
interface OtherIf {}

class ParentCl {}
class ChildCl extends ParentCl {}
class OtherCl {}

    public static void main(String[] args) {
        ChildIf cI = null;
        ParentIf pI = null;
        OtherIf oI = null;
        ChildCl cC = null;
        ParentCl pC = null;
        OtherCl oC = null;

        cI = (ChildIf)oI; //case1 - fine

        cC = (ChildCl)oC; //case2 - inconvertible types

        cI = (ChildIf)oC; //case3 - fine
    }
}


但是更尴尬的是,我不知道为什么其他两个陈述还可以。

我看不到OtherIf和ChildIf之间的任何连接。那么当case1的两个接口之间没有“扩展”时,如何将OtherIf强制转换为ChildIf?

最佳答案

cI = (ChildIf)oI;


很好,因为oI可以是同时实现ChildIf和OtherIf的类的实例。

cI = (ChildIf)oC;


很好,因为oC可能是扩展OtherClass的类的实例,而anec实现了ChildIf

10-02 22:01