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

查看:20
本文介绍了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");
    }
}

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

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?

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

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 {

}

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

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 中的一个新特性,它允许 interface 提供一个实现.在 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)

添加 default 方法,或将方法从 abstract 更改为 default,不会破坏与预先存在的二进制文件的兼容性,但可能如果预先存在的二进制文件尝试调用该方法,则会导致 IncompatibleClassChangeError.如果限定类型 T 是两个接口 IJ 的子类型,其中 Icode> 和 J 声明了一个具有相同签名和结果的 default 方法,并且 IJ 都不是一个另一个的子接口.

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天全站免登陆