接口方法可以有一个体? [英] Can an interface method have a body?

查看:129
本文介绍了接口方法可以有一个体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道界面就像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));
   }    
}



参见




  • 接口方法的Oracle文档

    对于Java 8中所有有趣的事情,请阅读关于Java 8的一切

    For all interesting things in Java 8 read Everything about Java 8

    这篇关于接口方法可以有一个体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆