Java 接口中静态方法和默认方法的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27833168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference Between static and default methods in interface
提问by Vipin Menon
I was learning through interfaces when I noticed that you can now define static and default methods in an interface.
当我注意到您现在可以在接口中定义静态和默认方法时,我正在通过接口学习。
public interface interfacesample2 {
public static void method() {
System.out.println("hello world");
}
public default void menthod3() {
System.out.println("default print");
}
}
Kindly explain the difference of the two and also if there's an example of when we would use this would be nice. A little confused on Interfaces.
请解释两者的区别,如果有一个我们何时使用它的例子会很好。对接口有点困惑。
回答by EyasSH
A static method is a method that applies to the class 'namespace', so to speak. So a static
method foo
of interface Interface
is accessed by Interface.foo()
. Note that the function call does not apply to any particular instanceof the interface.
静态方法是一种适用于类“命名空间”的方法,可以这么说。所以接口的static
方法是通过. 请注意,函数调用不适用于接口的任何特定实例。foo
Interface
Interface.foo()
A default implementation bar
on the other hand, is called by
bar
另一方面,默认实现由
Interface x = new ConcreteClass();
x.bar();
A static
interface method cannot know about the this
variable, but a default implementation can.
一个static
接口方法不能知道的this
变量,而是一个默认的实现可以。
回答by Shail016
1. explain the difference of the two
1.说明两者的区别
Static interface methods are like static class methods(here they belong to Interface only). Where as the default interface methods provide default implementation
of interface methods (which implementing classes may override
)
But remember in case a class is implementing more than one interface with same default
method signature then the implementing class needs to override the default method
静态接口方法就像静态类方法(这里它们只属于接口)。作为默认接口方法提供default implementation
的接口方法(可能实现类override
)
但请记住,如果类是implementing more than one interface with same default
方法签名,则实现类needs to override the default method
You can find a simple example below (can DIY for different cases)
你可以在下面找到一个简单的例子(可以针对不同情况DIY)
public class Test {
public static void main(String[] args) {
// Accessing the static member
I1.hello();
// Anonymous class Not overriding the default method
I1 t = new I1() {
@Override
public void test() {
System.out.println("Anonymous test");
}
};
t.test();
t.hello("uvw");
// Referring to class instance with overridden default method
I1 t1 = new Test2();
t1.test();
t1.hello("xyz");
}
}
interface I1 {
void test();
//static method
static void hello() {
System.out.println("hello from Interface I1");
}
// default need not to be implemented by implementing class
default void hello(String name) {
System.out.println("Hello " + name);
}
}
class Test2 implements I1 {
@Override
public void test() {
System.out.println("testing 1234...");
}
@Override
public void hello(String name) {
System.out.println("bonjour" + name);
}
}
2. when we would use this would be nice.
2.我们什么时候使用这个会很好。
That depends on your problem statement. I would say Default methods are useful, if you need same implementation for a method in your specification in all the classes in that contract, Or it may be used like Adapter
classes.
这取决于您的问题陈述。我会说默认方法很有用,如果您需要在该合同中的所有类中对规范中的方法进行相同的实现,或者可以像Adapter
类一样使用它。
here is a good read: https://softwareengineering.stackexchange.com/questions/233053/why-were-default-and-static-methods-added-to-interfaces-in-java-8-when-we-alread
这是一个很好的阅读:https: //softwareengineering.stackexchange.com/questions/233053/why-were-default-and-static-methods- added-to-interfaces-in-java-8-when-we-alread
also below oracle doc explains default & static methods for evolving existing interfaces:
也在 oracle 文档下面解释了用于发展现有接口的默认和静态方法:
Users who have classes that implement interfaces enhanced with new default or static methods do not have to modify or recompile them to accommodate the additional methods.
拥有使用新默认或静态方法增强接口的类的用户不必修改或重新编译它们以适应附加方法。
http://docs.oracle.com/javase/tutorial/java/IandI/nogrow.html
http://docs.oracle.com/javase/tutorial/java/IandI/nogrow.html
回答by KennyC
According to Oracle's Javadocs: http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
根据 Oracle 的 Javadocs:http: //docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.
默认方法使您能够向库的接口添加新功能,并确保与为这些接口的旧版本编写的代码的二进制兼容性。
静态方法是与定义它的类相关联的方法,而不是与任何对象相关联的方法。类的每个实例共享其静态方法。
Normally, static method in interface is used as Helper methods while default method are used as a default implementation for classes that implements that interface.
通常,接口中的静态方法用作 Helper 方法,而默认方法用作实现该接口的类的默认实现。
Example:
例子:
interface IDemo {
//this method can be called directly from anywhere this interface is visible
static int convertStrToInt(String numStr) {
return Integer.parseInt(numStr);
}
//getNum will be implemented in a class
int getNum();
default String numAsStr() {
//this.getNum will call the class's implementation
return Integer.toString(this.getNum());
}
}
回答by Abhijeet
This linkhas some useful insights, have listed few of them here.
这个链接有一些有用的见解,这里列出了一些。
default& staticmethods have bridged down the differences between interfacesand abstractclasses.
默认和静态方法弥合了接口和抽象类之间的差异。
Interface defaultmethods:
接口默认方法:
- It helps in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
- It helps in extending interfaces without having the fear of breaking implementation classes.
- 它有助于避免实用程序类,例如所有 Collections 类方法都可以在接口本身中提供。
- 它有助于扩展接口而不必担心破坏实现类。
Interface staticmethods:
接口静态方法:
- They are part of interface, we can't use it for implementation class objects.
- It helps in providing security by not allowing implementation classes to override them.
- 它们是接口的一部分,我们不能将它用于实现类对象。
- 它通过不允许实现类覆盖它们来帮助提供安全性。
Like to quote another useful reference.
喜欢引用另一个有用的参考。
回答by Premraj
we cannot execute Interfacesample2.menthod3();
because it is not static method. In order to execute method3()
we need an instance of Interfacesample2
interface.
我们无法执行,Interfacesample2.menthod3();
因为它不是静态方法。为了执行,method3()
我们需要一个Interfacesample2
接口实例。
Please find the following practical example:
请找到以下实际示例:
public class Java8Tester {
public static void main(String args[]){
// Interfacesample2.menthod3(); Cannot make a static reference to the non-static method menthod3 from the type Interfacesample2
new Interfacesample2(){ }.menthod3();// so in order to call default method we need an instance of interface
Interfacesample2.method(); // it
}
}
interface Interfacesample2 {
public static void method() {
System.out.println("hello world");
}
public default void menthod3() {
System.out.println("default print");
}
}
回答by stinger
Differences between static and default methods in Java 8:
Java 8 中静态方法和默认方法的区别:
1) Default methods can beoverriden in implementing class, while static cannot.
1)默认方法可以在实现类中被覆盖,而静态方法不能。
2) Static method belongs onlyto Interface class, so you can only invoke static method on Interface class, not on class implementing this Interface, see:
2)静态方法只属于Interface类,所以只能在Interface类上调用静态方法,不能在实现这个Interface的类上调用,见:
public interface MyInterface {
default void defaultMethod(){
System.out.println("Default");
}
static void staticMethod(){
System.out.println("Static");
}
}
public class MyClass implements MyInterface {
public static void main(String[] args) {
MyClass.staticMethod(); //not valid - static method may be invoked on containing interface class only
MyInterface.staticMethod(); //valid
}
}
3) Both class and interface can havestatic methods with same names, and neither overrides other!
3)类和接口都可以有同名的静态方法,并且都不能覆盖其他!
public class MyClass implements MyInterface {
public static void main(String[] args) {
//both are valid and have different behaviour
MyClass.staticMethod();
MyInterface.staticMethod();
}
static void staticMethod(){
System.out.println("another static..");
}
}
回答by Vijay
Here is my view:
这是我的观点:
static methodin interface:
接口中的静态方法:
You can call it directly (InterfacetA.staticMethod())
Sub-class will not be able to override.
Sub-class may have method with same name as staticMethod
可以直接调用(InterfacetA.staticMethod())
子类将无法覆盖。
子类可能有与 staticMethod 同名的方法
default methodin interface:
接口中的默认方法:
You can not call it directly.
Sub-class will be able to override it
你不能直接调用它。
子类将能够覆盖它
Advantage:
优势:
static Method:You don't need to create separate class for utility method.
default Method:Provide the common functionality in default method.
静态方法:您不需要为实用程序方法创建单独的类。
默认方法:提供默认方法中的常用功能。
回答by Satish Keshri
Interface default methods:
接口默认方法:
It helps in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
它有助于避免实用程序类,例如所有 Collections 类方法都可以在接口本身中提供。
It helps in extending interfaces without having the fear of breaking implementation classes.
它有助于扩展接口而不必担心破坏实现类。
Interface static methods:
接口静态方法:
They are part of interface, we can't use it for implementation class objects.
它们是接口的一部分,我们不能将它用于实现类对象。
It helps in providing security by not allowing implementation classes to override them.
它通过不允许实现类覆盖它们来帮助提供安全性。
Now how static method providing security. Let's see an example.
现在静态方法如何提供安全性。让我们看一个例子。
interface MyInterface {
/*
* This is a default method so we need not to implement this method in the implementation classes
*/
default void newMethod() {
System.out.println("Newly added default method in Interface");
}
/*
* This is a static method. Static method in interface is similar to default method except that we cannot override them in the implementation classes. Similar to default methods, we need to implement these methods in implementation classes so we can safely add them to the existing interfaces.
*/
static void anotherNewMethod() {
System.out.println("Newly added static method in Interface");
}
/*
* Already existing public and abstract method We must need to implement this method in implementation classes.
*/
void existingMethod(String str);
}
public class Example implements MyInterface {
// implementing abstract method
public void existingMethod(String str) {
System.out.println("String is: " + str);
}
public void newMethod() {
System.out.println("Newly added default method in Class");
}
static void anotherNewMethod() {
System.out.println("Newly added static method in Class");
}
public static void main(String[] args) {
Example obj = new Example();
// calling the default method of class
obj.newMethod();
// calling the static method of class
obj.anotherNewMethod();
// calling the static method of interface
MyInterface.anotherNewMethod();
// calling the abstract method of interface
obj.existingMethod("Java 8 is easy to learn");
}
}
Here obj.newMethod();
printing class implementation logic, means we can change the logic of that method inside implementation class.
这里obj.newMethod();
打印类实现逻辑,意味着我们可以在实现类内部更改该方法的逻辑。
But obj.anotherNewMethod();
printing class implementation logic ,but not changed interface implementation. So if any encryption-decryption logic written inside that method you can't change.
但是obj.anotherNewMethod();
打印类实现逻辑,但没有改变接口实现。因此,如果在该方法中编写了任何加密解密逻辑,则无法更改。
回答by Rakesh Prajapati
Starting Java 8 interface can also have static method. Like static method of a class, static method of an interface can be called using Interface name.
启动 Java 8 接口也可以有静态方法。与类的静态方法一样,接口的静态方法也可以使用接口名称来调用。
Example
例子
public interface Calculator {
int add(int a, int b);
int subtract(int a, int b);
default int multiply(int a, int b) {
throw new RuntimeException("Operation not supported. Upgrade to UltimateCalculator");
}
static void display(String value) {
System.out.println(value);
}
}
Difference between static and default method of interface is default method supports inheritance but static method does not. Default method can be overridden in inheriting interface.
接口的静态方法和默认方法的区别在于默认方法支持继承而静态方法不支持。可以在继承接口中覆盖默认方法。
Here is good read about interface default method and static method. Interface Default Method in Java 8
这是关于接口默认方法和静态方法的好读物。Java 8 中的接口默认方法
回答by Jay Rajput
All good answers here. I would like to add another practical usage of the static function in the interface. The tip is coming from the book - Effective Java, 3rd Edition by Joshua Bloch in Chapter2: Creating and Destroying Object.
所有好的答案都在这里。我想在界面中添加静态函数的另一个实际用法。该技巧来自 Joshua Bloch 在第 2 章:创建和销毁对象中的《Effective Java,第 3 版》一书。
Static functions can be used for static factory methods.
Static factory method are methods which return an object. They work like constructor. In specific cases, static factory method provides more readable code than using constructor.
静态工厂方法是返回对象的方法。他们像构造函数一样工作。在特定情况下,静态工厂方法提供比使用构造函数更易读的代码。
Quoting from the book - Effective Java, 3rd Edition by Joshua Bloch
引用这本书 - Effective Java,第 3 版,Joshua Bloch
Prior to Java 8, interfaces couldn't have static methods. By convention, static factory methods for an interface named Type were put in a noninstantiable companion class (Item 4) named Types.
在 Java 8 之前,接口不能有静态方法。按照惯例,名为 Type 的接口的静态工厂方法放在名为 Types 的不可实例化的伴随类(第 4 项)中。
Author gives an example of Collections where such static factory method is implemented. Checking on the code, Josh Bloch can be seen as first author of Collections class. Although Collections is a class and not interface. But the concept still applies.
作者给出了一个实现这种静态工厂方法的集合示例。查看代码,Josh Bloch 可以看作是 Collections 类的第一作者。尽管 Collections 是一个类而不是接口。但这个概念仍然适用。
For example, the Java Collections Framework has forty-five utility implementations of its interfaces, providing unmodifiable collections, synchronized collections, and the like. Nearly all of these implementations are exported via static factory methods in one noninstantiable class (java.util.Collections). The classes of the returned objects are all nonpublic.
例如,Java Collections Framework 有 45 个接口的实用程序实现,提供不可修改的集合、同步的集合等。几乎所有这些实现都是通过一个不可实例化的类 (java.util.Collections) 中的静态工厂方法导出的。返回对象的类都是非公开的。
Further he explains that API is not only smaller, it helps with the code readability and API ease..
他进一步解释说,API 不仅更小,而且有助于代码可读性和 API 易用性。
It is not just the bulk of the API that is reduced but the conceptual weight: the number and difficulty of the concepts that programmers must master in order to use the API. The programmer knows that the returned object has precisely the API specified by its interface, so there is no need to read additional class documentation for the implementation class.
减少的不仅仅是 API 的大部分,还有概念权重:程序员为了使用 API 必须掌握的概念的数量和难度。程序员知道返回的对象恰好具有其接口指定的 API,因此无需阅读实现类的额外类文档。
Here is one of the static method from java.util.Collections class:
这是 java.util.Collections 类的静态方法之一:
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
return new UnmodifiableCollection<>(c);
}