Java中default关键字的用途是什么? [英] What is the purpose of the default keyword in Java?

查看:2412
本文介绍了Java中default关键字的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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 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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆