接口方法可以有一个体? [英] Can an interface method have a body?
问题描述
我知道界面就像100%纯抽象类。所以,它不能有方法实现。但是,我看到了一个奇怪的代码。任何人都可以解释一下吗?
I know that an interface is like a 100% pure abstract class. So, it can't have method implementation in it. But, I saw a strange code. Can anyone explain it?
代码段:
interface Whoa {
public static void doStuff() {
System.out.println("This is not default implementation");
}
}
编辑:
我的IDE是Intellij Idea 13.1。项目SDK是java 7< 1.7.0_25>。 IDE未显示任何编译器错误。但是,当我在命令行编译代码时,我收到以下消息。
My IDE is Intellij Idea 13.1. The project SDK is java 7 <1.7.0_25>. The IDE is not showing any compiler error. But, When I compile the code at command line I am getting the following message.
Whoa.java:2: error: modifier static not allowed here
public static void doStuff() {
^
推荐答案
从 Java 8 ,您可以在默认方法之外定义接口中的静态方法。
From Java 8 you can define static methods in interfaces in addition to default methods.
-
静态方法是一种与定义它的类相关联的方法,而不是与任何对象相关联的方法。该类的每个实例都共享其静态方法。
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.
这使您可以更轻松地在库中组织辅助方法;您可以在同一个接口中保留特定于接口的静态方法,而不是在单独的类中。
This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.
以下示例定义了一个检索<$的静态方法c $ c> ZoneId 对应于时区标识符的对象;如果没有与给定标识符对应的 ZoneId
对象,它将使用系统默认时区。 (因此,您可以简化方法 getZonedDateTime
)
The following example defines a static method that retrieves a ZoneId
object corresponding to a time zone identifier; it uses the system default time zone if there is no ZoneId
object corresponding to the given identifier. (As a result, you can simplify the method getZonedDateTime
)
这是代码:
public interface TimeClient {
// ...
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}