1. Overview
1.概述
From Java 9, private methods can be added to interfaces in Java. In this short tutorial, let’s discuss how we can define these methods and their benefits.
从Java 9开始,私人方法可以被添加到Java的接口中。在这个简短的教程中,让我们讨论一下如何定义这些方法以及它们的好处。
2. Defining Private Methods in Interfaces
2.在接口中定义私有方法
Private methods can be implemented static or non-static. This means that in an interface we are able to create private methods to encapsulate code from both default and static public method signatures.
私有方法可以实现静态或非静态。这意味着在一个接口中,我们能够创建私有方法来封装来自默认和静态公共方法签名的代码。
First, let’s look at how we can use private methods from default interface methods:
首先,让我们看看我们如何从默认的接口方法中使用私有方法。
public interface Foo {
default void bar() {
System.out.print("Hello");
baz();
}
private void baz() {
System.out.println(" world!");
}
}
bar() is able to make use of the private method baz() by calling it from it’s default method.
bar()能够通过从它的默认方法中调用私有方法baz()来利用它。
Next, let’s add a statically defined private method to our Foo interface:
接下来,让我们给我们的Foo接口添加一个静态定义的私有方法。
public interface Foo {
static void buzz() {
System.out.print("Hello");
staticBaz();
}
private static void staticBaz() {
System.out.println(" static world!");
}
}
Within the interface, other statically defined methods can make use of these private static methods.
在接口内,其他静态定义的方法可以利用这些私有静态方法。
Finally, let’s call the defined default and static methods from a concrete class:
最后,让我们从一个具体的类中调用定义好的默认和静态方法。
public class CustomFoo implements Foo {
public static void main(String... args) {
Foo customFoo = new CustomFoo();
customFoo.bar();
Foo.buzz();
}
}
The output is the string “Hello world!” from the call to the bar() method and “Hello static world!” from the call to the buzz() method.
输出是调用bar()方法的字符串 “Hello world!”和调用buzz()方法的字符串 “Hello static world!
3. Benefits of Private Methods in Interfaces
3.接口中的私有方法的好处
Let’s talk about the benefits of private methods now that we have defined them.
既然我们已经定义了私有方法,我们就来谈谈它们的好处。
Touched on in the previous section, interfaces are able to use private methods to hide details on implementation from classes that implement the interface. As a result, one of the main benefits of having these in interfaces is encapsulation.
在上一节中提到,接口能够使用私有方法,向实现接口的类隐藏实现的细节。因此,在接口中拥有这些方法的主要好处之一就是封装。
Another benefit is (as with private methods in general) that there is less duplication and more re-usable code added to interfaces for methods with similar functionality.
另一个好处是(和一般的私有方法一样),对于具有类似功能的方法,可以减少重复,为接口添加更多可重用的代码。
4. Conclusion
4.总结
In this tutorial, we have covered how to define private methods within an interface and how we can use them from both static and non-static contexts. The code we used in this article can be found over on GitHub.
在本教程中,我们介绍了如何在接口中定义私有方法,以及如何从静态和非静态上下文中使用它们。我们在本文中使用的代码可以在GitHub上找到over。