Java 中的 "methods without access control can be declared more private in subclasses" 是什么意思?

What means "methods without access control can be declared more private in subclasses" in Java?

在java访问修饰符和继承主题中说了以下4点。第三点中的“more private”是什么意思?

  1. ...
  2. ...
  3. 没有访问控制声明的方法=>可以在子类中声明更私有
  4. ...

完整信息可在此Java Tutorial

中找到

可以在不在同一个包中的子 类 中重新定义没有访问控制声明的方法(覆盖在这里不是正确的词)。

package p1;
public class A {
    void m() {}
}


package p1;
public class B {
    //This does not work as class is in the same package and this would be an attempt to reduce visibility
    private void m() {}
}


package p2;
public class C extends A {
    //This works fine as class C does not 'see' the parent method
    private void m() {
    }
}

(This has a translation in Russian on RU.SO)

实际上没有'more'或'less private'这样的术语。而是使用 'more / less visible'。

题中表述错误。方法不能变得不那么明显,因为那样会破坏 Liskov substitution principle:

Let Φ(x) be a property provable about objects x of type T. Then Φ(y) should be true for objects y of type S where S is a subtype of T.

这是 GitHub 上的一个存储库,它说明了继承 Java 中的包访问方法的所有可能变体。 https://github.com/NickVolynkin/PackageAccessTest

public class Parent {

    //package access
    void foo() {
    }
}

public class ChildPublic extends Parent {

    // Legal
    @Override
    public void foo() {
    }
}

public class ChildProtected extends Parent {
    // Legal
    @Override
    protected void foo() {
    }
}

public class ChildPrivate extends Parent {
    // Illegal
    /*
    @Override
    private void foo() {
    }
    */
}

public class SamePackageAccessTest {
    {
        new Parent().foo();

        //these have overriden foo()
        new ChildPublic().foo();
        new ChildProtected().foo();

        //this one had not overriden foo()
        new ChildPrivate().foo();
    }
}

package otherpackage;
import test.*;
public class OtherPackageAccessTest {

    {
        //Legal!
        new ChildPublic().foo();

        //illegal
        /*
        new ParentPackage().foo();
        new ChildProtected().foo();
        new ChildPrivate().foo();
        */

    }
}

Methods declared without access control => can be declared more private in subclasses

这是错误的。这恰恰相反。用任何级别的访问控制声明的方法必须用该级别或更高级别 public 覆盖:在这种情况下,访问级别基础 class 是 'default',因此您可以使用 publicprotected.

与 Google 文档所说的相反,您 不能 覆盖 private. 请参阅 JLS §8.4.8.3:

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:

  • If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method has package access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.