【问题标题】:Java dynamic binding failedJava 动态绑定失败
【发布时间】:2019-02-26 23:35:06
【问题描述】:

我真的不明白为什么下面的代码不起作用。我希望B.f 被打印出来。

public class Main {
    public static void main(String[] args) {
        B b = new B();
        b.g();
    }
}

class A {
    void g() {
        f();    /* or this.f() */
    }
}

class B extends A {
    void f() {
        System.out.println("B.f");
    }
}

编译器抱怨:

Main.java:13: error: cannot find symbol
        f();    /* or this.f() */
        ^
  symbol:   method f()
  location: class A
1 error

据我了解,A.g 中的this 的动态类型始终为B。这样一来,Java的动态方法查找应该可以为this.f找到B.f,然后执行。

【问题讨论】:

    标签: java class methods dynamic this


    【解决方案1】:

    这将不起作用,因为 A 类不知道方法 f()。如果您不想在 A 中定义 f(),则可以将 f() 设为抽象,您也可以将 A 类设为抽象:

    abstract class A {
        void g() {
            f();    /* or this.f() */
        }
    
        abstract void f();
    }
    
    class B extends A {
        void f() {
            System.out.println("B.f");
        }
    }
    

    【讨论】:

      【解决方案2】:

      Java 的动态调度只能看到在当前类或其超类上定义的方法。由于 A 没有定义方法,因此无法看到 B 定义了它,因此您会收到错误。

      但是,如果该方法是私有以外的任何访问,则 B 可以覆盖它,因此即使通过“A”实例类型访问该方法,对 B 实例上的方法的调用也将动态分派到 B 的实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 2010-12-10
        相关资源
        最近更新 更多