gpt4 book ai didi

java - 为什么我不能使用已实现接口(interface)的静态方法?

转载 作者:太空狗 更新时间:2023-10-29 22:33:48 26 4
gpt4 key购买 nike

作为专家,您在 Java 8 中知道,接口(interface)可以有静态方法,这些方法本身有实现。

正如我在相关教程中所读到的,实现此类接口(interface)的类可以使用其静态方法。但是,我有一个问题,在这里,我用一个比我所拥有的更简单的例子来展示它

public interface Interface1{
public static void printName(){
System.out.println("Interface1");
}
}

当我实现这样的接口(interface)时

public class Class1 implements Interface1{
public void doSomeThing() {
printName();
}
}

我遇到了编译错误。

The method printName() is undefined for the type Class1

有什么问题?

最佳答案

From the Java Language Specification ,

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:

  • [...]

A class C inherits from its direct superclass and direct superinterfaces all abstract and default (§9.4) methods m for which all of the following are true:

  • [...]

A class does not inherit static methods from its superinterfaces.

所以那个方法是不被继承的。

可以静态导入成员

import static com.example.Interface1.printName;
...
printName();

或将其与完全限定的类型名称一起使用

com.example.Interface1.printName();

或导入 printName 所属的类型并使用其短名称调用它

import static com.example.Interface1;
...
Interface1.printName();

关于java - 为什么我不能使用已实现接口(interface)的静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com