本文介绍了为什么我不能在接口中声明静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个话题说的最多 - 不能在接口中声明静态方法的原因是什么?

The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?

public interface ITest {
    public static String test();
}

上面的代码给了我以下错误(至少在 Eclipse 中):接口方法 ITest.test() 的非法修饰符;只允许公共和抽象".

The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".

推荐答案

这里有几个问题.第一个是声明一个静态方法而不定义它的问题.这就是

There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between

public interface Foo {
  public static int bar();
}

public interface Foo {
  public static int bar() {
    ...
  }
}

第一个是不可能的,原因是 Espo 提到:你不知道哪个实现类是正确的定义.

The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.

Java 可以允许后者;事实上,从 Java 8 开始,它确实如此!

Java could allow the latter; and in fact, starting in Java 8, it does!

这篇关于为什么我不能在接口中声明静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:36