Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ClassCastException vs.“;“不可转换类型”;编译错误_Java_Casting_Compiler Errors_Classcastexception - Fatal编程技术网

Java ClassCastException vs.“;“不可转换类型”;编译错误

Java ClassCastException vs.“;“不可转换类型”;编译错误,java,casting,compiler-errors,classcastexception,Java,Casting,Compiler Errors,Classcastexception,所以我想知道Java在什么情况下抛出ClassCastException,以及何时出现“不可转换类型”编译错误。我想这是关于接口的 我的意思是,有了接口,情况就更困难了。例如: interface SomeInterface {} class SomeClass {} SomeClass someObject = new SomeClass(); SomeInterface someInterface = (SomeInterface)someObject; 抛出ClassCastExcep

所以我想知道Java在什么情况下抛出
ClassCastException
,以及何时出现“不可转换类型”编译错误。我想这是关于接口的

我的意思是,有了接口,情况就更困难了。例如:

interface SomeInterface {}
class SomeClass {}
SomeClass someObject = new SomeClass();
SomeInterface someInterface  = (SomeInterface)someObject;

抛出
ClassCastException
虽然在编译时很清楚,
SomeClass
对象不能被强制转换到
SomeInterface
关于接口没有必要。强制转换告诉编译器您将从另一种类型的变量引用一种类型的实例

当强制转换建议的类型转换不可能时,就会出现编译错误

i、 e.
String s=(String)新整数(1)

有时可能,有时不可能,代码会编译,但您可能会得到ClassCastException

i、 e

  • 如果使用接口,则通常会出现运行时异常
  • 如果使用,则通常有一个编译时间 错误
例:

vs


查看IS-A测试…它不必涉及接口,但使用接口是遇到它的常见地方。更重要的是,虽然您可以“偷偷”通过编译器,但如果强制转换无效,则无法避免运行时ClassCastException。
Object o = ...;
String s = (String) o;//Depending on the content of o, this line may throw a ClassCastException
interface Fruct{}
class Banana{}
Fruct fruct = (Fruct) new Banana();       // Compile OK, but throw a ClassCastException
class Fruct{}           
class Banana{}
Fruct fruct = (Fruct) new Banana();          // Compile-Time-Error: Inconvertible types