+ 1
How can casting sub class into other sub class in java
Hey if I have a sub class named a and other sub class named b how can I casting a to b by method in test class
4 ответов
+ 5
Okay.
In your test class:
public B getB(A a){
if(a instanceof B) return (B)a;
return a;
}
If you want to cast something you can do this with ().
Maybe you know that you can cast a double to int.
double num = 5.3;
int result = (int) num;
It is the same way. You only need to be careful with downcasting.
In your case: every b is also an instance of A. So you can always upcast. But not every instance of A is an instance of B.
A a = new A(); is not an instance of B. It is only an instance of favoriteGame and A.
That's why you need to check with instanceof.
Hope this helps :)
+ 3
Just for clarification:
Test is the super class, a extends Test and b extends a?
+ 2
thank you for helping me 🌹🌹
+ 1
thanks for your reply ; the super class named favoriteGame