Java中default关键字的用途是什么? [英] What is the purpose of the default keyword in Java?
问题描述
Java中的接口类似于类,但
接口的主体可以包含仅抽象方法和final
字段
(常量)。
An interface in Java is similar to a class, but the body of an interface can include only abstract methods and
final
fields (constants).
最近,我看到一个问题,看起来像这样
Recently, I saw a question, which looks like this
interface AnInterface {
public default void myMethod() {
System.out.println("D");
}
}
根据接口定义,仅抽象方法是允许的。为什么它允许我编译上面的代码?什么是默认
关键字?
According to the interface definition, only abstract methods are allowed. Why does it allow me to compile the above code? What is the default
keyword?
另一方面,当我尝试编写下面的代码时,那么说修饰符默认不允许
On the other hand, when I was trying to write below code, then it says modifier default not allowed here
default class MyClass{
}
而不是
class MyClass {
}
有人能告诉我默认
关键字的用途吗?是否只允许在界面内?它与默认
(无访问修饰符)有何不同?
Can anyone tell me the purpose of the default
keyword? Is it only allowed inside an interface? How does it differ from default
(no access modifier)?
推荐答案
这是Java 8中的一项新功能,允许接口
到提供实施。在Java 8中描述 JLS-13.5.6。接口方法声明读取(部分)
It's a new feature in Java 8 which allows an interface
to provide an implementation. Described in Java 8 JLS-13.5.6. Interface Method Declarations which reads (in part)
添加
默认
方法,或将方法从abstract
更改为default
,不会破坏与预先存在的二进制文件的兼容性,但可能如果预先存在的二进制文件尝试调用该方法,则会导致IncompatibleClassChangeError
。如果限定类型T
是两个接口的子类型,I
和J
,其中I
和J
声明默认值
具有相同签名和结果的方法,I
和J
都是子接口另一个。
Adding a
default
method, or changing a method fromabstract
todefault
, does not break compatibility with pre-existing binaries, but may cause anIncompatibleClassChangeError
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
andJ
, where bothI
andJ
declare adefault
method with the same signature and result, and neitherI
norJ
is a subinterface of the other.
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中default关键字的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!