为什么在Java中接口变量默认是静态的和最终的?


当前回答

界面是双方之间的契约,是不变的,刻在石头上,因此是最终的。参见契约式设计。

其他回答

在Java中,接口不允许你声明任何实例变量。使用在接口中声明的变量作为实例变量将返回编译时错误。

你可以声明一个常量变量,使用不同于实例变量的静态final。

static -因为接口不能有任何实例。最后,因为我们不需要改变它。

摘自Philip Shaw的Java接口设计常见问题解答:

接口变量是静态的,因为Java接口不能自己实例化;变量的值必须在不存在实例的静态上下文中赋值。最后一个修饰符确保分配给接口变量的值是一个真正的常量,不能被程序代码重新分配。

Java不允许在接口中定义抽象变量和/或构造函数。解决方案:简单地在你的接口和你的实现之间挂起一个抽象类,它只像这样扩展抽象类:

 public interface IMyClass {

     void methodA();
     String methodB();
     Integer methodC();

 }

 public abstract class myAbstractClass implements IMyClass {
     protected String varA, varB;

     //Constructor
     myAbstractClass(String varA, String varB) {
         this.varA = varA;
         this.varB = VarB;
     }

     //Implement (some) interface methods here or leave them for the concrete class
     protected void methodA() {
         //Do something
     }

     //Add additional methods here which must be implemented in the concrete class
     protected abstract Long methodD();

     //Write some completely new methods which can be used by all subclasses
     protected Float methodE() {
         return 42.0;
     }

 }

 public class myConcreteClass extends myAbstractClass {

     //Constructor must now be implemented!
     myClass(String varA, String varB) {
         super(varA, varB);
     }

     //All non-private variables from the abstract class are available here
     //All methods not implemented in the abstract class must be implemented here

 }

如果您确定以后不希望将抽象类与其他接口一起实现,也可以使用没有任何接口的抽象类。请注意,你不能创建一个抽象类的实例,你必须先扩展它。

(“protected”关键字意味着只有扩展类才能访问这些方法和变量。)

斯派罗

接口可以由任何类实现,如果该值被其中一个实现类改变了,那么就会对其他实现类产生误导。接口基本上是指将两个相互关联但又不同的实体组合在一起。因此,在接口内部声明的变量将隐式是final的,也是静态的,因为接口不能被实例化。