我需要一种方法来选择应该调用谁的方法。
我正在调用一个父方法,该父方法使用"this"调用其方法之一。问题是我在类中覆盖了该方法,因此当调用父方法时,它会调用我的方法而不是它的方法。
public class MainTest
{
public static class A
{
public String m1()
{
return this.m2();
}
public String m2()
{
return "A.m2() called";
}
}
public static class B extends A
{
@Override
public String m1()
{
return "B.m1() called";
}
@Override
public String m2()
{
return "B.m2() called";
}
public String m3()
{
return super.m1();
}
}
public static void main(String[] args)
{
System.out.println(new B().m3());
}
}
我想实现"A.m2(( 调用",但实际输出是"B.m2(( 调用">
正如您在 B
中覆盖了 m2()
一样,那么让A.m2()
运行而不是B.m2()
的唯一方法是在 B.m2()
中调用 super.m2()
。
即使您在B.m3()
中调用super.m1();
,在A.m1()
中调用this.m2()
仍会导致被覆盖的B.m2()
运行。
如果您不想在 B.m2()
中包含super.m2()
(或者不希望在所有情况下都这样做(,那么唯一的选择是创建一个您不会在 B
中覆盖的其他方法(并从 A.m1()
调用它 - 您可能也必须更改或创建另一个A.m1()
(:
public static class A {
public String m1(){ //you may need a different method to call from B.m3()
return this.anotherM2();
}
public String m2(){
return "A.m2() called";
}
public String anotherM2() {
return "A.m2() called";
}
}
要实现您想要的,您需要在 B.m3
中调用 super.m2()
。
呼叫super.m1()
不起作用,因为A.m1
呼叫this.m2()
。 this
的运行时类型 B
(您从未创建过 A
对象,因此它不能是运行时类型 A
(,因此将调用 B
中的m2
。您只能打电话给super.m2()
来实现您想要的。
您可以看到以下过程:
-B.m3 做 super.m1 是什么意思 A.m1
-A.m1 这样做.m2,其中这是 B,因此称为 B.m2