gpt4 book ai didi

java - 了解方法继承

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

以下是JLS的方法定义方法继承:

A class C inherits from its direct superclass and direct superinterfaces all abstract and default (§9.4) methods m for which all of the following are true:

  • m is a member of the direct superclass or a direct superinterface, D, of C.

  • m is public, protected, or declared with package access in the same package as C.

  • No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m.

  • No concrete method inherited by C from its direct superclass has a signature that is a subsignature of the signature of m.

  • There exists no method m' that is a member of the direct superclass or a direct superinterface, D', of C (m distinct from m', D distinct from D'), such that m' from D' overrides the declaration of the method m.

第四个项目符号我不清楚。甚至不可能在同一个类中同时声明抽象方法和非抽象方法。您不能解释一下该规则的实际含义吗?

最佳答案

C 可能会从其直接父类(super class)及其实现的接口(interface)继承方法(在 Java 8 中,它甚至可以从接口(interface)继承默认实现)。

假设C扩展B并实现I

B 包含一个方法:

public void m (String s)

我包含一个方法(可能具有默认实现):

public void m (String s)

第四个项目符号意味着由于B的存在,C不会继承Im方法code> 的 m 方法。 C 只会继承 Bm 方法。

如果你看similar section in the JLS for Java 7 :

8.4.8. Inheritance, Overriding, and Hiding

A class C inherits from its direct superclass and direct superinterfaces all abstract and non-abstract methods of the superclass and superinterfaces that are public, protected, or declared with default access in the same package as C, and are neither overridden (§8.4.8.1) nor hidden (§8.4.8.2) by a declaration in the class.

Methods are overridden or hidden on a signature-by-signature basis.

If, for example, a class declares two public methods with the same name (§8.4.9), and a subclass overrides one of them, the subclass still inherits the other method.

If the method not inherited is declared in a class, or the method not inherited is declared in an interface and the new declaration is abstract, then the new declaration is said to override it.

If the method not inherited is abstract and the new declaration is not abstract, then the new declaration is said to implement it.

您会注意到没有类似的语言,如果添加有问题的项目符号是为了解决 Java 8 中引入的默认接口(interface)方法,这是有意义的。

关于java - 了解方法继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28715909/

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