为什么人们会选择在接口中使用静态方法而不是默认方法
Why would one ever choose to use a static method in an interface instead of a default method
首先,在你试图解释什么是接口、静态方法和默认方法之前,我不推荐它,因为这不是问题所在。我还想说明这不是与 abstract/default 方法之间的区别或什么是方法相关的问题的重复。这不是问题。
所以在一个接口中,可以有默认方法和静态方法。两者都有一个实现。两者都可以在实现接口的 classes 中使用。我看到的主要区别是静态方法不能通过对象运行,而默认方法可以。但是,它们都有实现,而不是 "instance" 实现接口的两个相同类型的对象没有位于接口内部的实例变量...因为接口变量都是 static 和 final .
所以因为唯一的主要区别是一个可以通过对象运行而一个只能通过 class 运行...但是他们做同样的事情,为什么要用静态方法呢。在classes中,可以通过对象实例调用静态方法。在接口中,你不能。默认值似乎只有一个额外的功能,那么为什么选择使用静态而不是默认值呢?
-谢谢
However, they both have implementation, and are not "instance" in the sense that the two objects of the same type that implement the interface do not have instance variables located inside the interface... because interface variables are all static and final.
不,你错了。默认方法委托给抽象方法。抽象方法在实现接口的具体 classes 中实现。具体 classes 非常有实例字段。
示例:
interface Counter {
void add(int i);
default void increment() {
this.add(1);
}
}
实施
class ConcreteCounter implements Counter {
private int value = 0;
@Override
public void add(int i) {
this.value += i;
}
}
静态方法,就像 classes 中的静态方法一样,不能调用实例方法,并且在接口 class 本身上调用,而不是在该接口的实例上调用。在上面的例子中,你可以有
interface Counter {
static Counter createDefault() {
return new ConcreteCounter();
}
void add(int i);
default void increment() {
this.add(1);
}
}
此静态方法不可能作为默认方法实现:
必须创建一个计数器才能创建一个计数器是没有意义的。
举个更具体的例子,我们就拿List
接口的sort()
方法来说吧。它对列表的元素进行排序,并且是一种默认方法。它不可能是静态方法:静态方法不会在 List 的实例上调用,因此它不可能对其元素进行排序。
所以,基本上,接口中默认方法和静态方法之间的区别与 class 中静态方法和实例方法之间的区别相同。
首先,在你试图解释什么是接口、静态方法和默认方法之前,我不推荐它,因为这不是问题所在。我还想说明这不是与 abstract/default 方法之间的区别或什么是方法相关的问题的重复。这不是问题。
所以在一个接口中,可以有默认方法和静态方法。两者都有一个实现。两者都可以在实现接口的 classes 中使用。我看到的主要区别是静态方法不能通过对象运行,而默认方法可以。但是,它们都有实现,而不是 "instance" 实现接口的两个相同类型的对象没有位于接口内部的实例变量...因为接口变量都是 static 和 final .
所以因为唯一的主要区别是一个可以通过对象运行而一个只能通过 class 运行...但是他们做同样的事情,为什么要用静态方法呢。在classes中,可以通过对象实例调用静态方法。在接口中,你不能。默认值似乎只有一个额外的功能,那么为什么选择使用静态而不是默认值呢?
-谢谢
However, they both have implementation, and are not "instance" in the sense that the two objects of the same type that implement the interface do not have instance variables located inside the interface... because interface variables are all static and final.
不,你错了。默认方法委托给抽象方法。抽象方法在实现接口的具体 classes 中实现。具体 classes 非常有实例字段。
示例:
interface Counter {
void add(int i);
default void increment() {
this.add(1);
}
}
实施
class ConcreteCounter implements Counter {
private int value = 0;
@Override
public void add(int i) {
this.value += i;
}
}
静态方法,就像 classes 中的静态方法一样,不能调用实例方法,并且在接口 class 本身上调用,而不是在该接口的实例上调用。在上面的例子中,你可以有
interface Counter {
static Counter createDefault() {
return new ConcreteCounter();
}
void add(int i);
default void increment() {
this.add(1);
}
}
此静态方法不可能作为默认方法实现: 必须创建一个计数器才能创建一个计数器是没有意义的。
举个更具体的例子,我们就拿List
接口的sort()
方法来说吧。它对列表的元素进行排序,并且是一种默认方法。它不可能是静态方法:静态方法不会在 List 的实例上调用,因此它不可能对其元素进行排序。
所以,基本上,接口中默认方法和静态方法之间的区别与 class 中静态方法和实例方法之间的区别相同。