类型转换时的不一致性(错误:不兼容的类型)

huangapple go评论78阅读模式
英文:

Inconsistencies while typecasting (Error: Incompatible types)

问题

这个程序可以顺利编译。

     
interface X{}
class A{
    public void mA(){
        System.out.println("mA of A");
    }
}
class Demo{
    public static void main(String args[]){
        X  ob=null;
        A a1=null;
        
        ob=(X) a1; //合法
        a1=(A)ob; //合法
    }
}

但是下面的代码有问题:

interface X{}
final class A{
    public void mA(){
        System.out.println("mA of A");
    }
}
class Demo{
    public static void main(String args[]){
        X  ob=null;
        A a1=null;
        
        ob=(X) a1; //非法
        a1=(A)ob; //非法
    }
}

错误信息:
错误:不兼容的类型:无法将 A 转换为 X
ob=(X) a1; //非法
^
1 错误
编译失败。

英文:

This Program Compile without any Issue.

     
interface X{}
class A{
    public void mA(){
        System.out.println("mA of A");
    }
}
class Demo{
    public static void main(String args[]){
        X  ob=null;
        A a1=null;
        
        ob=(X) a1; //Legal
        a1=(A)ob; //Legal
    }
}

But Below code have issues ?

    
interface X{}
final class A{
    public void mA(){
        System.out.println("mA of A");
    }
}
class Demo{
    public static void main(String args[]){
        X  ob=null;
        A a1=null;
        
        ob=(X) a1; //Illegal
        a1=(A)ob; //Illegal
    }
}

Error:
 error: incompatible types: A cannot be converted to X
 ob=(X) a1; //Illegal
            ^
1 error
Compilation failed.

答案1

得分: 7

A 的实例永远不会同时也是 X 的实例。然而,在第一个例子中,a1 可能是某个虚构类的实例,该类扩展了 A 并实现了 X,因此强制转换是可以的。

在第二个例子中,没有 A 的子类,因为它是 final 的。由于 A 没有实现 X,永远不会有一个 A 的实例也是 X 的实例。因此,编译器足够智能,能够理解强制转换将始终失败,因此会给出错误消息。

英文:

Instances of class A will never also be instances of X. However, in the first example, it is possible that a1 is an instance of some hypothetical class that extends A and implements X, so the cast is fine.

In the second example, there are no subclasses of A because it is final. Since A does not implement X, there will never be an instance of A that is also an instance of X. Therefore, the compiler is smart enough to understand that the cast will always fail and so gives you an error message.

huangapple
  • 本文由 发表于 2020年5月5日 21:24:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/61614252.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定