Surely it's possible to have ClassCastException with subclassing. Here's a simple example:
public abstract class SelfBound<T extends SelfBound<T>> { protected abstract T getThis(); public void doSomething(T instance) { } public final void doSomethingWithThis() { doSomething(getThis()); } public final void doSomethingWithThisUnsafe() { doSomething((T) this); } public static class A extends SelfBound<A> { @Override protected A getThis() { return this; } } public static class B extends SelfBound<A> { @Override public void doSomething(A instance) { super.doSomething(instance); } @Override protected A getThis() { return null; } } public static void main(String[] args) { new B().doSomethingWithThisUnsafe(); } }
Output:
Exception in thread "main" java.lang.ClassCastException: SelfBound$B cannot be cast to SelfBound$A at SelfBound$B.doSomething(SelfBound.java:1) at SelfBound.doSomethingWithThisUnsafe(SelfBound.java:6) at SelfBound.main(SelfBound.java:28)
It's not so clear what do you mean by "without subclassing SelfBound". As SelfBound is an abstract class, you cannot call its methods without subclassing it, thus you cannot have any exception when calling its methods.
SelfBoundbut that might have.Serializable val = new Serializable() {}; return (SomeSubclass) val;inside the overridengetThis().Tin so thatdoSomethingWithThisUnsafethrows a CCE