简体   繁体   中英

ClassCastException vs. “inconvertible types” compilation error

So I wanted to know on what situations Java throws ClassCastException and when it's "inconvertible types" compilation error. I guess it's something about interfaces.

I mean with interfaces there is more difficult situation. For example:

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

throws ClassCastException thought It's clear at compile time, that SomeClass object cannot be casted to SomeInterface .

It's not necessary about interfaces. A cast tells the compiler that you're going to reference an instance of one type, from a variable of another type.

When the type conversión suggested by the cast is impossible, you get a compilation error.

ie String s = (String) new Integer(1);

When sometimes it's possible and sometimes not, the code compiles, but you may get a ClassCastException.

ie

Object o = ...;
String s = (String) o;//Depending on the content of o, this line may throw a ClassCastException
  • If you use a interfaces , then generally you have a runtime exception.
  • If you use a class , then generally you have a compile time error.

ex.:

interface Fruct{}
class Banana{}
Fruct fruct = (Fruct) new Banana();       // Compile OK, but throw a ClassCastException

vs.

class Fruct{}           
class Banana{}
Fruct fruct = (Fruct) new Banana();          // Compile-Time-Error: Inconvertible types

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