How can casting sub class into other sub class in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

2nd May 2020, 11:10 PM
Anas Omari
Anas Omari - avatar
4 Answers
+ 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 :)
2nd May 2020, 11:37 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Just for clarification: Test is the super class, a extends Test and b extends a?
2nd May 2020, 11:22 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
thank you for helping me 🌹🌹
2nd May 2020, 11:40 PM
Anas Omari
Anas Omari - avatar
+ 1
thanks for your reply ; the super class named favoriteGame
2nd May 2020, 11:27 PM
Anas Omari
Anas Omari - avatar