Java : ClassCastException with Examples

ClassCastException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most ClassCastException methods.


Summary

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

Class diagram

class Base {
}

class SubA extends Base {
}

class SubB extends Base {
}
final Base base = new SubA();

// Cast OK!
final SubA subA = (SubA) base;

// Cast NG!
try {
    final SubB subB = (SubB) base;
} catch (ClassCastException e) {
    System.out.println("ClassCastException!");
}

// Result
// ↓
//ClassCastException!

Constructors

ClassCastException ()

Constructs a ClassCastException with no detail message.

final var e = new ClassCastException();
System.out.println(e); // java.lang.ClassCastException

ClassCastException (String s)

Constructs a ClassCastException with the specified detail message.

final var e = new ClassCastException("abcde");
System.out.println(e); // java.lang.ClassCastException: abcde
System.out.println(e.getMessage()); // abcde

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page