简体   繁体   English

Java动态绑定失败

[英]Java dynamic binding failed

I don't really understand why the following code doesn't work. 我不太明白为什么以下代码不起作用。 I expect Bf to be printed out. 我希望Bf被打印出来。

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

The compiler complains: 编译器抱怨:

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

From my understanding, the dynamic type of the this in Ag is always of B . 据我了解, Ag this的动态类型始终是B As a result, Java's dynamic method lookup should be able to find Bf for this.f and then execute it. 结果,Java的动态方法查找应该能够找到this.f Bf ,然后执行它。

Java's dynamic dispatch can only see methods defined on the current class or its superclasses. Java的动态调度只能看到在当前类或其父类上定义的方法。 Since A does not define the method it cannot see that B defines it and you get an error. 由于A未定义方法,因此无法看到B定义了该方法,并且会出现错误。

However if the method is any access other than private, B can override it and hence calls to the method on an instance of B will be dynamically dispatched to B's implementation even when accessing the method through an "A" instance type. 但是,如果该方法是除私有之外的任何访问,则B可以覆盖它,因此即使在通过“ A”实例类型访问该方法时,对B实例的方法调用也将动态分派到B的实现。

This will not work as class A doesn't have any idea about method f(). 这将无法正常工作,因为类A对方法f()没有任何了解。 If you do not want to define f() in A, you could make f() abstract instead for which You can make class A also abstract : 如果您不想在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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM