Reputation: 228
If you have two different classes A and B, and B is a subclass of A, you cannot cast as follows:
A a = new A();
B b = new B();
A newA = (A)b;
Is there a way to enable the above code to work (no alterations to the above code) without the JVM throwing a ClassCastException?
------------EDIT----------
Sorry, I made a mistake in the code in the above question. The correct version is below:
A a = new A();
B b = new B();
B newB = (B)a;
Upvotes: 2
Views: 4322
Reputation: 120268
B
already has an is-a relationship to A
. You don't need to cast it....You can throw a B at any method or reference that expects/points to an A
.
Based on your edit -- there is something wrong with your design if you want to do this. While a B
is-a A
, the opposite is NOT true. An A
is not a B
. In other words, since B
extends A
, it probably has methods/properties on it that are NOT defined on A
. If you cast an A
to a B
, then methods that accept that reference might try to invoke a method it believes is on the instance, since you told the compiler that it got a B
, when in reality the underlying A
does not have the required method.
Casting here will only lead to pain and failure.
Upvotes: 4
Reputation: 147164
With new code, no you can't do that. You'd have to create a new object:
B newB = new B(a);
or
B newB = B.of(a);
A non-abstract non-leaf class should generally be avoided anyway. Also, since 1.5 (released 2004), there shouldn't be much of the casting syntax about.
Upvotes: 1
Reputation: 236114
If B
is a subclass of A
the above should work, and the cast would be unnecessary:
A a = new A();
B b = new B();
A newA = b; // no need to cast!
Upvotes: 2