Java 使用另一个son方法调用被son覆盖的父方法
我想从子方法调用父方法,但我不知道父方法是如何工作的: 父级Java 使用另一个son方法调用被son覆盖的父方法,java,extension-methods,overriding,Java,Extension Methods,Overriding,我想从子方法调用父方法,但我不知道父方法是如何工作的: 父级A具有以下方法:myMethod(双d) instanceOfB.myMethod(d)工作正常 问题是instanceOfB.anotherMethod(…)它只是执行instanceOfB.myMethod(d) 我希望B的实例运行父对象的myMethod。 有什么建议吗?你做错了什么。它确实调用super.myMethod()。我快速地组装了这段代码以进行测试 public class Test { public sta
A
具有以下方法:myMethod(双d)
instanceOfB.myMethod(d)
工作正常
问题是instanceOfB.anotherMethod(…)
它只是执行instanceOfB.myMethod(d)
我希望B
的实例运行父对象的myMethod
。有什么建议吗?你做错了什么。它确实调用super.myMethod()。我快速地组装了这段代码以进行测试
public class Test {
public static void main(String ... args) {
B b= new B();
b.anotherMethod(); //the output is 1 which is correct
b.myMethod(2); //the output is somth and then 2 which is correct
}
public static class A {
public void myMethod(double d) {
System.out.println(d);
}
}
public static class B extends A{
//overrides
public void myMethod(double d){
doSomthing();
super.myMethod(d);
}
private void doSomthing() {
System.out.println("somth");
}
public void anotherMethod(){
super.myMethod(1);
}
}
}
为我们提供A类的实现。你是说
b.anotherMethod(…)
运行A
的myMethod
?我也这么认为。但是你的陈述和我的例子有什么关系?你是在向我们展示你认为很好吗?这些是内部类,但这并不意味着anotherMethod()中的super.myMethod()不运行它。它确实有用,但是,它不起作用,我在那里尝试了最简单的方法,与你写它的方式完全相同。。
public class Test {
public static void main(String ... args) {
B b= new B();
b.anotherMethod(); //the output is 1 which is correct
b.myMethod(2); //the output is somth and then 2 which is correct
}
public static class A {
public void myMethod(double d) {
System.out.println(d);
}
}
public static class B extends A{
//overrides
public void myMethod(double d){
doSomthing();
super.myMethod(d);
}
private void doSomthing() {
System.out.println("somth");
}
public void anotherMethod(){
super.myMethod(1);
}
}
}