gpt4 book ai didi

java - JLS 如何指定术语 "abstract method"、 "concrete method"和 "default method"?

转载 作者:行者123 更新时间:2023-12-04 16:50:24 27 4
gpt4 key购买 nike

我在一些 StackOverflow 答案中看到了术语抽象方法、具体方法和默认方法的“不同”定义。

Java 语言规范给出的真正定义是什么?请在您的答案中包含相关的支持 JLS 引用资料。

最佳答案

抽象方法

Java 语言规范 (JLS) Section 8.4.3.1 中定义了一个抽象方法。作为:

An abstract method declaration introduces the method as a member, providing its signature (§8.4.2), result (§8.4.5), and throws clause if any (§8.4.6), but does not provide an implementation (§8.4.7).



在实践中,抽象方法是定义了签名但没有提供实现的任何方法。例如,接口(interface)中的方法和使用 abstract 限定的方法。抽象类中的关键字都是抽象方法:
public interface Foo {
void someAbstractMethod();
}

public abstract class Bar {

public abstract someAbstractMethod();

// ...

}

具体方法

根据 JLS Section 8.4.3.1 ,具体方法定义为:

A method that is not abstract may be referred to as a concrete method.



在实践中,这意味着提供了实现的任何方法:
public FooImpl implements Foo {

@Override
public void someAbstractMethod() {
// ... some implementation ...
}

}

默认方法

默认方法在 JLS Section 9.4 中定义:

A default method is an instance method declared in an interface with the default modifier. Its body is always represented by a block, which provides a default implementation for any class that implements the interface without overriding the method. Default methods are distinct from concrete methods (§8.4.3.1), which are declared in classes, and from private interface methods, which are neither inherited nor overridden.



同一部分还添加:

An interface can declare static methods, which are invoked without reference to a particular object. static interface methods are distinct from default methods, which are instance methods.



默认方法是为特定目的而创建的。在 JDK 8 中,函数式接口(interface)被添加到 Java 中。这需要更新接口(interface)以包含功能方法,但这样做需要这些接口(interface)的所有现有实现(包括在 3rd 方库和框架中)都需要提供实现。相反,Java 团队引入了默认方法,它们是提供默认实现的接口(interface)方法,当重写类没有提供实现时使用该实现。

这不应该用作抽象类的替代品。它旨在用于特定目的,并且应该用于该目的。

在实践中,默认方法是使用 default 创建的。关键词:
public interface Foo {

public default void someMethod() {
// ... some default implementation ...
}
}

这个默认实现可以在具体的子类中被覆盖:
public class FooImpl implements Foo {

@Override
public void someMethod() {
// ... some overriding implementation ...
}
}

此外,根据 JLS Section 9.4.1.1 ,方法的默认实现(默认方法的主体)可以使用 super 在具体子类中访问。关键字,由接口(interface)名称限定:

An overridden default method can be accessed by using a method invocation expression (§15.12) that contains the keyword super qualified by a superinterface name.



例如:
public class FooImpl implements Foo {

@Override
public void someMethod() {
Foo.super.someMethod();
}
}

接口(interface)名称用作限定符,因为一个类可以实现多个接口(interface)(或者一个接口(interface)可以扩展多个接口(interface))。如需更多信息,请参阅 Explicitly calling a default method in Java .

关于java - JLS 如何指定术语 "abstract method"、 "concrete method"和 "default method"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59951096/

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