gpt4 book ai didi

java - 方法的动态调度和访问级别

转载 作者:行者123 更新时间:2023-12-02 05:40:06 25 4
gpt4 key购买 nike

考虑以下类:

public class A {
public void foo() {
System.out.println("A.foo()");
}

public void bar() {
System.out.println("A.bar()");
foo();
}
}

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

public static void main(String[]
args) {
A a = new B();
a.bar();
}
}

这段代码的输出是 A.bar()然后B.foo() 。我注意到,如果我将方法 foo() 的访问级别从 public 更改为至private输出是:A.bar()然后A.foo() .

为什么?

最佳答案

如果A.foo()是私有(private)的,那么它不能被子类覆盖——任何其他类基本上应该不知道私有(private)成员的存在。您无法覆盖您无法“看到”的成员。

来自section 8.4.8.1 of the JLS :

An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:

  • ...

  • One of the following is true:

    • mA is public.
    • mA is protected.
    • mA is declared with package access in the same package as C, and either C declares mC or mA is a member of the direct superclass of C.
    • mA is declared with package access and mC overrides mA from some superclass of C.
    • mA is declared with package access and mC overrides a method m' from C (m' distinct from mC and mA), such that m' overrides mA from some superclass of C.

关于java - 方法的动态调度和访问级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com