Java 如何在实现该接口的类中更改接口变量值

Java 如何在实现该接口的类中更改接口变量值,java,Java,我创建了一个界面,如下所示: public interface CalculatorInterface { int x=10; int y=15; int z=x+y; public void add1(); } public class AdvClass2 implements CalculatorInterface { public static void main(String[] args) { int x=50; S

我创建了一个界面,如下所示:

public interface CalculatorInterface 
{ 
      int x=10; int y=15; int z=x+y; 
      public void add1();
}
public class AdvClass2 implements CalculatorInterface {

    public static void main(String[] args) {
       int x=50;
       System.out.println("X value is" +x);
    }

    @Override
    public void add1() {
        System.out.println("I am in Add Method");       
    }}
然后我创建了一个类来实现它。该类如下所示:

public interface CalculatorInterface 
{ 
      int x=10; int y=15; int z=x+y; 
      public void add1();
}
public class AdvClass2 implements CalculatorInterface {

    public static void main(String[] args) {
       int x=50;
       System.out.println("X value is" +x);
    }

    @Override
    public void add1() {
        System.out.println("I am in Add Method");       
    }}

但是规则说我不允许正确更改接口变量值。有人能告诉我我做错了什么吗?

界面中的变量默认为静态最终变量(您可以将其称为静态常量)变量,所以您只能给它赋值一次,以后不能更改它的值


检查此站点的最终关键字-

实际上您正在更改
主功能中的局部变量。此变量与您在界面中声明的变量不同,默认情况下,该变量实际上是
公共、静态和最终的。但对局部变量没有这样的限制

此外,如果局部范围中存在同名变量,则该变量优先于外部范围中同名变量

编辑:

正如我前面解释的,您在main函数中将
x
声明为局部变量,它不同于接口中的变量
x
。如果试图更改接口
x
变量时出现编译错误,请在主函数中执行以下操作:

public static void main(String[] args) {
   x=50;
   System.out.println("X value is" +x);
}

现在,您将看到一个编译错误,告诉您无法分配接口的x变量。

由于接口不能直接实例化,因此默认情况下接口变量是静态的和最终的。我们不允许改变它们

接口不能包含任何实现。Java接口只能包含方法签名和字段

我认为你需要一个更好的设计。因此,界面应该如下所示:

public interface ICalculator {

public int add1(int a, int b); // this is the method signature, not the implementation.

} 
然后在
AdvClass2
中,您可以实现
add1
方法:

@Override
public int add1(int a, int b) {
   int result = a + b;

   return result;
}

1使用大字母开头2。我很惊讶这是法律吗?它编译吗?接口cammot有“变量”,但从Java文档中我看到,一旦任何类实现了任何接口,接口中声明的任何变量都不能在类中更改。我对自己能够成功编译感到惊讶。@Swarup,因为我解释了要注意的重要事项,以便您理解
为什么没有得到编译错误
是因为您没有更改接口变量
x
。相反,您正在使用
intx=50创建一个全新的局部变量xint
,就像我在编辑过的答案中所做的那样,您将看到一个编译错误explanation@Swarup如果您的疑问得到解决,您能否将其中一个答案标记为已接受?这只会帮助社区。