2

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;
7
  • class B extends A { }, right? Should work even without the cast. Mar 19, 2012 at 18:38
  • In any situation in which an object of type A is called for, an object of type B is a viable substitute, no casting needed. Mar 19, 2012 at 18:39
  • @OliCharlesworth It may make sence in the context that dscer is working... this is just a simple example Mar 19, 2012 at 18:39
  • Yes, you can "cast" like that. It's a meaningless cast, because b is already of type A, but it's permitted. Mar 19, 2012 at 18:41
  • @AlejoBrz: I misread the question, but apparently the OP also miswrote the question, so we're back where we started! Mar 19, 2012 at 18:44

4 Answers 4

4

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.

2

I think you can simply assign:

A newA = b;
2

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!
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.