Java does not support this. You can leverage polymorphism to treat an instance of B
as and instance of A
but not the other way around.
The reason you cannot do this is because there is no type-safe way to guarantee that your instance of A
is in fact an instance of B
(you could cast the instance but even if you did you would only be guaranteeing yourself an exception at execution time).
The best way to tell if there is a type-safe, polymorphic relationship between types is to test this statement for validity:
Any instance of some type is an instance of some other type.
For instance:
Any instance of Dog is an instance of Mammal.
Any instance of Mammal is an instance of Dog.
Notice that the first example is true while the second is false. What you are trying to do in your code example is exactly like trying to treat any mammal as a dog - even though it may be true occasionally it is not true categorically which means the compiler will not allow it.
Again, for times when it could be true you must cast the reference but this opens you up for exceptions at execution time. Your specific example above is one of those times when an exception would occur as we can clearly see that you have instantiated an instance of type A
.