[英]How to choice what method should be called when use polymorphism
I need a way to choice who method should be called.我需要一种方法来选择应该调用谁的方法。
I'm calling a parent method who calls one of its methods using "this".我正在调用一个使用“this”调用其方法之一的父方法。 The problem is that I override that method in my class so when call the parent method then It calls to my method instead of its method.问题是我在我的类中覆盖了该方法,所以当调用父方法时,它会调用我的方法而不是它的方法。
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());
}
}
I want to achieve "A.m2() called", but the actual output is "B.m2() called"我想实现“A.m2() 调用”,但实际输出是“B.m2() 调用”
As you have overridden m2()
in B
, then only way to get A.m2()
to run instead of B.m2()
is to call super.m2()
inside B.m2()
.正如你所覆盖的m2()
中B
,那么只有这样,才能A.m2()
而不是运行B.m2()
是调用super.m2()
内B.m2()
Even if you're calling super.m1();
即使你正在调用super.m1();
in B.m3()
, the call to this.m2()
in A.m1()
will still cause the overridden B.m2()
to run.在B.m3()
调用this.m2()
在A.m1()
将仍然导致重写B.m2()
来运行。
If you don't want to have super.m2()
inside B.m2()
(or don't want that in all cases), then the only alternative is to create a different method that you don't override in B
(and call that from A.m1()
- you may have to change or create another A.m1()
too):如果您不想在super.m2()
B.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";
}
}
you can see the following process:您可以看到以下过程:
-B.m3 does super.m1 what means A.m1 -B.m3 做 super.m1 是什么意思 A.m1
-A.m1 does this.m2, where this is B, for that reason B.m2 is being called -A.m1 执行 this.m2,这里是 B,因此调用 B.m2
To achieve what you want, you need to call super.m2()
in B.m3
.为了实现你想要的,你需要在B.m3
调用super.m2()
。
Calling super.m1()
wouldn't work because A.m1
calls this.m2()
.调用super.m1()
不起作用,因为A.m1
调用this.m2()
。 this
is of runtime type B
(you have never created an A
object so it can't be of runtime type A
), so the m2
in B
would be called. this
是运行时类型B
(您从未创建过A
对象,因此它不能是运行时类型A
),因此将调用B
的m2
。 You can only call super.m2()
to achieve what you want.您只能调用super.m2()
来实现您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.