简体   繁体   English

Java 8 - 接口是否不再是抽象的?

[英]Java 8 - Are interfaces not abstract anymore?

Up until now, interfaces in Java couldn't implement any method. 到目前为止,Java中的接口无法实现任何方法。 By definition, they were only a collection of method signatures with no body. 根据定义,它们只是没有正文的方法签名的集合。

But it seems this changed with Java 8. 但似乎这改变了Java 8。

Is this true? 这是真的? What are 'default methods' exactly? 什么是'默认方法'? What is a 'functional interface'? 什么是“功能界面”? Anybody care explain this to me? 有人在乎向我解释这个吗? Things on Google are pretty confusing. 谷歌上的事情非常令人困惑。

In Java 8, Interfaces can now have default methods which are actually implemented. 在Java 8中, Interfaces现在可以具有实际实现的default方法。 This was done to help avoid problems for users who implement an Interface that has had a change made to it, so they don't have to update all of their classes. 这样做是为了帮助避免实现已对其进行更改的Interface用户出现问题,因此他们不必更新所有类。

You add this functionality by adding the default keyword to your method signature. 您可以通过将default关键字添加到方法签名来添加此功能。

See The Java Tutorials 请参阅Java教程

What are 'default methods' exactly? 什么是'默认方法'?

Default methods provide a mechanism for you to add implementation to an interface without making it an abstract class. 默认方法提供了一种机制,您可以将实现添加到接口,而不必将其作为抽象类。

The main use case for default methods has been the task of adding methods to an interface without breaking other people's code. 默认方法的主要用例是在不破坏其他人的代码的情况下向接口添加方法的任务。 However, they also let you "mix in" functionality through implementing an interface, which is a very powerful addition to Java's type system that used to allow only a single line of implementations. 但是,它们还允许您通过实现接口来“混合”功能,这是Java类型系统的一个非常强大的补充,过去只允许一行实现。

What is a 'functional interface'? 什么是“功能界面”?

Functional interface, on the other hand, is a way to tell the compiler that your interface is going to have exactly one method. 另一方面,功能接口是一种告诉编译器您的接口将只有一个方法的方法。 In exchange for that the compiler gives you a much shorter syntax for defining implementations of your interface, dramatically shortening the code that used to depend on anonymous classes. 作为交换,编译器为您提供了更短的语法来定义接口的实现,大大缩短了以前依赖于匿名类的代码。

In addition to the two features above, interfaces let you define static functions to be shared among all implementations. 除了上面的两个功能外,接口还允许您定义要在所有实现之间共享的静态函数。 Like default implementations, this adds a "second dimension" to inheriting implementation, because it lets you share code through interface implementation. 与默认实现一样,这为继承实现添加了“第二维”,因为它允许您通过接口实现共享代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM