【问题标题】:define common variables across multiple classes using interfaces使用接口跨多个类定义公共变量
【发布时间】:2012-08-02 09:04:56
【问题描述】:

我有一个示例界面

 public interface SampleVariables {
int var1=0;
int var2=0;
}

我想在多个类中使用 var1 和 var2 我正在尝试使用

public class InterfaceImplementor  extends Message  implements SampleVariables{

private int var3;

public int getVar1(){
    return var1;
}

public void setVar1(int var1){
    SampleVariables.var1=var1; // ** error here in eclipse which says " remove final modifier of 'var1' " Though I have not defined it as final
}

public int getVar3() {
    return var3;
}

public void setVar3(int var3) {
    this.var3 = var3;
}

}

其中类 Message 是我尝试使用的预定义类,我无法在类 Message 中定义 var1、var2。

有没有更好的方法来做到这一点?还是我错过了一些非常简单的东西?

【问题讨论】:

    标签: java interface


    【解决方案1】:

    接口中的所有字段隐式都是静态和最终的,因此您在上面发出警告。详情请见this SO question

    在我看来,您想要一个带有这些变量的基类,但正如您所指出的,您不能这样做,因为您是从 3rd 方类派生的。

    我不会从那个 3rd-party 类派生,因为你不控制它的实现。我宁愿创建一个类包装它并提供您的附加功能。如果/当该第 3 方类发生更改,您可以限制您随后必须进行的更改的范围,这让您感到一定程度的舒适。

    不幸的是,Java 不支持 mixins,而这正是您在这里想要实现的。

    【讨论】:

      【解决方案2】:

      interface 默认情况下 变量static final 你不能改变那里的价值,即。你不能这样做SampleVariables.var1=var1;

      你能做的就是

      public class InterfaceImplementor  extends Message { // do not implement interface here
      
      private int var3;
      private int var1;
      
      public void setVar1(int var1){
          this.var1=var1; // will work
      }
      

      并访问interfaceSampleVariables.var1的变量

      【讨论】:

        【解决方案3】:

        由于Interface的成员变量是default static, final,所以你不能在初始化后再次reassign这个值。

        Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

        Java Language Specification

        【讨论】:

          【解决方案4】:

          您应该为此使用抽象类。

          示例:

          public abstract class AbstractClass {
              protected int var1;
          }
          class SubClass1 extends AbstractClass {
          
          }
          class SubClass2 extends AbstractClass {
          
          }
          

          这样SubClass1 和SubClass2 将有一个var1。请注意,您可以对 getter 和 setter 执行相同的操作,但为了说明这一点,这更短。

          【讨论】:

            猜你喜欢
            • 2015-01-29
            • 1970-01-01
            • 2013-05-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多