java - 为什么人们会选择在接口(interface)中使用静态方法而不是默认方法

标签 java interface static default

首先,在你试图解释什么是接口(interface)、静态方法和默认方法之前,我不推荐它,因为这不是问题所在。我还想解决这不是与抽象/默认方法之间的区别或什么是抽象/默认方法相关的问题的重复。这不是问题。

所以在一个接口(interface)中,可以有默认方法和静态方法。两者都有一个实现。两者都可以在实现接口(interface)的类中使用。我看到的主要区别是静态方法不能通过对象运行,而默认方法可以。但是,它们都有实现,并且在实现接口(interface)的两个相同类型的对象没有位于接口(interface)内部的实例变量的意义上不是“实例”......因为接口(interface)变量都是静态的和最终的。

所以因为唯一的主要区别是一个可以通过对象运行,而一个只能通过类运行...但它们做同样的事情,为什么要用静态方法呢。在类中,您可以通过对象实例调用静态方法。在接口(interface)中,你不能。默认值似乎只有一个额外的功能,那么为什么要选择使用静态而不是默认值呢?

-谢谢

最佳答案

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.

不,你错了。默认方法委托(delegate)给抽象方法。抽象方法在实现接口(interface)的具体类中实现。具体类非常有实例字段。

例子:

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;
    }
}

静态方法,就像类中的静态方法一样,不能调用实例方法,是在接口(interface)类本身上调用的,而不是在这个接口(interface)的实例上调用的。在上面的例子中,你可以有

interface Counter {
    static Counter createDefault() {
        return new ConcreteCounter();
    }

    void add(int i);
    default void increment() {
       this.add(1);
    }
}

此静态方法不可能作为默认方法实现: 必须创建一个计数器才能创建一个计数器是没有意义的。

举个更具体的例子,我们以List接口(interface)的sort()方法为例。它对列表的元素进行排序,并且是一种默认方法。它不可能是静态方法:静态方法不会在 List 的实例上调用,因此它不可能对其元素进行排序。

因此,基本上,接口(interface)中默认方法和静态方法之间的区别与类中静态方法和实例方法之间的区别相同。

关于java - 为什么人们会选择在接口(interface)中使用静态方法而不是默认方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55208830/

相关文章:

c# - 对基类强制执行重写方法

Java 二叉树中通用节点数组,无法创建 nil 节点

java - Spring Controller 不调用@Valid

java - 我将如何跨多行搜索一串单词

java - Guava TypeToken 和泛型类

c# - 在不使用扩展方法的情况下使用通用逻辑扩展 C# 接口(interface)

java - 在android上的2个距离点之间画线

java - 接口(interface)完整引用

multithreading - 在多核嵌入式 Rust 中,我可以使用静态 mut 进行单向数据共享吗?

python - 这个 Python "static variable"hack 可以使用吗?