java - 派生类可以减少对父类(super class)私有(private)方法的限制吗?

标签 java inheritance

基本上,你能做这样的事情吗?

class Base {
    private void foo(){
        println("Base");
    }
}
class Derived extends Base {
    public void foo(){
        println("Derived");
    }
}

最佳答案

在您的示例中,派生类的限制并没有减少。基类和派生类中的方法彼此无关。 方法Derived.foo()不会覆盖Base.foo()因此,Base.foo(的私有(private)访问) 并未通过 Derived.foo() 减少限制。

Java 语言规范 Section 8.4.8, Inheritance, Overriding, and Hiding 对此进行了介绍。 。

8.4.8.1 Overriding (by Instance Methods)

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:

  • A is a superclass of C.
  • C does not inherit mA.
  • The signature of mC is a subsignature (§8.4.2) of the signature of mA.
  • 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

简而言之,私有(private)方法不能被子类覆盖。如果您从基类调用私有(private)方法,它将调用该私有(private)方法,而不是子类中具有相同名称和签名的方法。

关于java - 派生类可以减少对父类(super class)私有(private)方法的限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685233/

相关文章:

java - 转换String时忽略空格

java - 对字符串和字符串数组 (String[]) 使用相同的 HashMapM<String,....>

java - 在 ContextLoaderListener 中获取服务器名称

java - 为什么 Android 应用程序因 UnsatisfiedLinkError 崩溃?

java - 如果要从需要 api key 的 Web 服务检索数据,如何使用 Spring?

javascript - "add method to prototype"是什么意思

java - java中使用通配符的hashmap无法赋值

inheritance - 在 GitLab CI 中使用 `extends` 时,哪些作业属性会被合并或覆盖?

java - 对象创建(状态初始化)和线程安全

c++ - 嵌套类中的继承