使用子的另一个方法调用被子重写的父方法



我想从子类调用父类方法,但我不知道父类方法是如何工作的:

A有方法:myMethod(double d)

public class B extends A{
    //overrides
    public void myMethod(double d){
         doSomthing();
         super.myMethod(d);
    }
    public void anotherMethod(...){
         super.myMethod(d);
    }
}

instanceOfB.myMethod(d) works fine.

问题是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);
        }
    }
}

最新更新