gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:48:17 24 4
gpt4 key购买 nike

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

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/

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