我的法典也这样看待,但这是一个简化版本:
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");
}
}
主要班级:
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:
我真的想要的是,当需要A时,即使用超级方法,在测试Arg与B一道使用时使用分级方法。
种姓也是一种选择,因为在实际法典中,与这里不同的是,我不知道这一方法的结果是否实际是B。
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");
}
}