Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用另一个son方法调用被son覆盖的父方法_Java_Extension Methods_Overriding - Fatal编程技术网

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);
        }

    }

}