强制调用基类方法 [英] Force invocation of base class method
问题描述
运行时的以下代码显然会打印出B1 / A2 / B2。现在,是否有可能打印A1 / A2 / B2(即A#method2()应该在A上调用method1(),而不是在B上调用?)
<注意:我没有这样的需要获得传递多态性,这个问题仅仅是出于好奇。
A类{
public void method1(){
System.out.println(A1);
}
public void method2(){
method1();
System.out.println(A2);
}
}
B类扩展A {
@Override public void method2(){
super.method2();
System.out.println(B2);
}
@Override public void method1(){
System.out.println(B1);
}
}
公共类Tmp {
public static void main(String args []){
B b = new B();
b.method2();
}
}
是, 你能行的。
在包 a 中定义A:
包a;
公共类A {
void method1(){
System.out.println(A1);
}
public void method2(){
method1();
System.out.println(A2);
}
}
在包中定义B b :
package b;
进口a.A;
公共类B扩展A {
@Override public void method2(){
super.method2();
System.out.println(B2);
}
void method1(){
System.out.println(B1);
}
}
将测试放入包 a 强>并运行它。结果是A1 / A2 / B2。当然这是不健康的:注意方法1上必须省略@Override - 如果你把它放回去,你会得到编译错误:
方法不会覆盖或实现超类型的方法
The following code when run obviously prints out "B1/A2/B2". Now, is it possible for it to print "A1/A2/B2" instead (i.e. A#method2() should invoke method1() on A, not on B)?
Note: I have no such need to get pass polymorphism, this question is out of curiosity only.
class A {
public void method1() {
System.out.println("A1");
}
public void method2() {
method1();
System.out.println("A2");
}
}
class B extends A {
@Override public void method2() {
super.method2();
System.out.println("B2");
}
@Override public void method1() {
System.out.println("B1");
}
}
public class Tmp {
public static void main(String args[]) {
B b = new B();
b.method2();
}
}
Yes, you can do it. Define A in package a:
package a;
public class A {
void method1() {
System.out.println("A1");
}
public void method2() {
method1();
System.out.println("A2");
}
}
Define B in package b:
package b;
import a.A;
public class B extends A {
@Override public void method2() {
super.method2();
System.out.println("B2");
}
void method1() {
System.out.println("B1");
}
}
Put your test in package a and run it. The result is A1/A2/B2. Of course this is unhealthy: note the necessary omission of @Override on method1 - if you put it back in, you will get a compiler error:
method does not override or implement a method from a supertype
这篇关于强制调用基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!