且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与Java混淆覆盖访问级别

更新时间:2023-12-03 22:57:16

覆盖方法可以'永远降低能见度。允许这样做会违反 Liskov替换原则,该原则声明(简化)派生类的所有对象 B 必须与基类 A 具有相同的属性。在这种情况下,一个这样的属性将是一个公共方法 foo 如果 B 具有该属性,它将丢失相同的方法,但它受保护

Overriding a method can't ever reduce the visibility. Allowing that would violate the Liskov Substitution Principle, which states (simplified) that all objects of a derived class B must have the same properties as the base class A. In this case one such "property" would be a public method foo which would be "lost" if B had that same method, but made it protected.

此外,因为私人方法不是继承的(尝试从派生类调用它!)它们不能被覆盖。您可以在基类中使用与 private 同名的 public 方法,但这不会覆盖,它只是一个具有相同名称的新方法,而不是其他关系。调用基类中的私有方法将调用 public 方法超类,即使在超类的对象上执行!

Also, since private methods are not inherited (try calling it from a derived class!) they can't ever be overriden. You can have a public method with the same name as a private one in the base class, but that's not overriding, it's simply a new method with the same name, but not other relation. Calls to the private method in the base class will not call the public method in the superclass, even when executed on objects of the superclass!

换句话说: private 方法从不使用运行时多态性。

In other words: private methods never use runtime polymorphism.

请参阅此示例:

public static class Base {
    public void callBoth() {
        foo();
        bar();
    }

    private void foo() {
        System.out.println("Base.foo");
    }

    protected void bar() {
        System.out.println("Base.bar");
    }
}

public static class Sub extends Base {
    public void foo() {
        System.out.println("Sub.foo");
    }

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

执行 new Sub时( ).callBoth()输出将是:


Base.foo
Sub.bar