简体   繁体   中英

Java Casting query Exception and error

在Java中,什么时候会出现不兼容的类型编译错误,什么时候会出现ClassCastException?

ClassCastException API Specifications clearly says:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

ClassCastException occurs at runtime because compiler believes that the cast may be a valid one.

Eg:

// The below line will compile but ClassCastException will be raised at runtime
Integer i = (Integer) new Object();

Incompatible type error can easily be resolved by the compiler at compile time itself. It simply looks if the class to which you are trying to cast a specific object falls in the same hierarchy.

Eg:

 String str = "abc"; <br>Integer number = (Integer) str;  
// Compile Error :  Integer and String are not in the same hierarchy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM