0

I'm aware that this could be a possible duplicate, but the other threads haven't solved my problem completely.

Let's say I have the following classes A and B which extend BasicClass.

public abstract class BasicClass {
   // ...
}

public class A extends BasicClass {
   // ...
}

public class B extends BasicClass {
   // ...
}

And now I want to cast class A to B dynamically.

a.getClass().cast(bClass.newInstance);

but every time I get an Exception.

java.lang.ClassCastException
at java.lang.Class.cast(Unknown Source)

Can you tell me why?

3 Answers 3

4

Because, in your inheritance hierarchy, a B is not an A. You cannot cast one to the other.

Sign up to request clarification or add additional context in comments.

Comments

1

Answer:

Because A is not extending B. (technicaly: A IS not B)

Explanation:

JVM performs "IS-A" test before it casts. If "IS-A" test fails, you will get "ClassCastException".(Just like you are getting now).

IS-A : IS-A test is to check whether a class(to be casted, in your case A) is in inheritance tree of the class(casted to, in your case B).

IS-A is the functional term, syntax to check IS-A test is instanceof". e.g a instanceof b : explanation of instance of:
LHS and RHS of the instance of must be the object. thus a and b are obeject. Their respective classes are checked for inheritance.

In your example following result will come.

a instanceof b : False

a instanceof basicObject : True

b instanceof a : False

b instanceof basicObject : True

basicObject instanceof a : False

basicObject instanceof b : False

You can only cast where result of instanceof is true.

2 Comments

Thanks for the explanation. I got it now. Would it be possible to cast A to B in two steps: A -> BasicClass -> B ?
@user2948795 A cast does not change the type of the object. Nothing can do that. Casting lets you view a reference of one type as a reference of another type.
0

Your hierarchy looks like this:

   BasicClass
      / \
     /   \
    A     B

A is not an ancestor of B, so it's impossible to cast an instance of B to A.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.