【问题标题】:Interface constant declaration example in Java's SDKJava SDK 中的接口常量声明示例
【发布时间】:2015-06-15 08:59:37
【问题描述】:

Java 的内置库 (JDK) 中是否有包含常量字段的接口示例?

documentation,可以在接口中定义常量声明,但我不记得见过这样的。

public interface OperateCar {

   // constant declarations, if any
   ...
}

【问题讨论】:

    标签: java interface constants


    【解决方案1】:

    例如

    package java.text;
    
    public interface CharacterIterator extends Cloneable
    {
        /**
         * Constant that is returned when the iterator has reached either the end
         * or the beginning of the text. The value is '\\uFFFF', the "not a
         * character" value which should not occur in any valid Unicode string.
         */
        public static final char DONE = '\uFFFF';
    

    但一般来说,在 JDK 接口中很难找到常量,因为它不符合语言约定。

    【讨论】:

      【解决方案2】:

      interface 的每个字段都隐含为public static final,因此使其成为常量。

      所以:

      public interface MyInterface {
          String FOO = "foo";
      }
      

      ... 等同于:

      public interface MyInterface {
          public static final String FOO = "foo";
      }
      

      【讨论】:

      • @AdamSkywalker 我做到了。尽管我将其解释为“你能在 Java 的源代码中找到一个包含常量的接口吗”,而是“接口中的常量声明看起来如何”。我猜是语义。
      猜你喜欢
      • 2019-04-24
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      相关资源
      最近更新 更多