gpt4 book ai didi

java - Java中default关键字的作用是什么?

转载 作者:IT老高 更新时间:2023-10-28 11:48:23 27 4
gpt4 key购买 nike

An interface in Java is similar to a class, but the body of an interface can include only abstract methods and final fields (constants).

最近看到一个问题,是这样的

interface AnInterface {
public default void myMethod() {
System.out.println("D");
}
}

根据接口(interface)定义,只允许使用抽象方法。为什么它允许我编译上面的代码? default 关键字是什么?

另一方面,当我尝试编写下面的代码时,它说 modifier default not allowed here

default class MyClass{

}

而不是

class MyClass {

}

谁能告诉我 default 关键字的用途?它只允许在接口(interface)内部吗?它与 default (无访问修饰符)有何不同?

最佳答案

这是 Java 8 中的一个新特性,它允许 interface 提供一个实现。在 Java 8 JLS-13.5.6. Interface Method Declarations 中描述内容为(部分)

Adding a default method, or changing a method from abstract to default, does not break compatibility with pre-existing binaries, but may cause an IncompatibleClassChangeError if a pre-existing binary attempts to invoke the method. This error occurs if the qualifying type, T, is a subtype of two interfaces, I and J, where both I and J declare a default method with the same signature and result, and neither I nor J is a subinterface of the other.

What's New in JDK 8说(部分)

Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.

关于java - Java中default关键字的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31578427/

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