My code looks sort of like this, but this is a simplified version:
class A:
public class A{
public void testArgs(A a){
System.out.println("A");
}
public void test(){
System.out.println("A");
}
}
class B:
public class B extends A{
public void testArgs(B a){
System.out.println("B");
}
public void test(){
System.out.println("B");
}
}
class Main:
public class Main{
public static void main(String[] args){
a(new B()).testArgs(new B()); // prints A
(new B()).testArgs(new B()); // prints B
a(new B()).test(); // prints B
}
public static A a(B b){
return b;
}
}
Why does a(new B()).testArgs(new B()) print A not B?
Is there some sort of way to workaround/fix this?
edit:
Clarification:
What I really want is the superclass method to be run when it is called with an A, and the subclass method to be run when testArgs is called with a B.
Casting also isn’t an option because in the actual code, unlike here, I don’t know whether the result of the method call is actually B or not.
edit:
Solution:
Thanks everyone for your answers. Thanks for the clarification on overriding. I used this to implement the desired behavior.
For anyone who has a similar problem in the future:
Change class B to
public class B extends A{
public void testArgs(A a){ // Corrected overriding, thanks
if(a instanceof B) // Check if it is an instance of B
System.out.println("B"); // Do whatever
else // Otherwise
super.testArgs(a); // Call superclass method
}
public void test(){
System.out.println("B");
}
}
The two
testArgsfunctions are different. One takes anAand the other takes aB. Thus, theBversion doesnt override theAversion. Sincea(new B())is of typeAandBextendsA, it is theAversion that will run.There is a “workaround”:
Then you will see
Bfor all 3 cases (becauseB‘stestArgswill overrideA‘stestArgs)