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


当前回答

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

其他回答

因为其他任何东西都是实现的一部分,而接口不能包含任何实现。

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”关键字意味着只有扩展类才能访问这些方法和变量。)

斯派罗

public interface A{
    int x=65;
}
public interface B{
    int x=66;
}
public class D implements A,B {
    public static void main(String[] a){
        System.out.println(x); // which x?
    }
}

这是解决方案。

System.out.println(A.x); // done

我认为这就是为什么界面变量是静态的原因之一。

不要在接口中声明变量。

接口:系统需求服务。

在接口中,变量默认由public,static,final访问修饰符赋值。 因为:

public:有时候接口可能被放在其他包中。所以它需要从项目中的任何地方访问变量。

static:这样不完整的类不能创建对象。所以在项目中,我们需要访问没有对象的变量,这样我们就可以在interface_filename.variable_name的帮助下访问

final:假设一个接口由许多类实现,并且所有类都试图访问和更新接口变量。这样会导致数据变化不一致,影响到其他类。所以它需要用final声明访问修饰符。

设想一个web应用程序,其中定义了接口并由其他类实现它。因为你不能创建一个接口的实例来访问变量,所以你需要一个静态关键字。由于它是静态的,任何值的变化都会反映到其他实现它的实例。所以为了防止这种情况,我们将其定义为最终结果。