Java - 接口(interface)成员的值

标签 java class interface

当我有一个实现接口(interface)的类时,该类的所有对象是否都具有与接口(interface)中的成员相同的值?

interface I {
 int element = 10;//since its public static final by default
 String s = "abcd"; 
}



class A implements I {
  private int timer;
  ...
  public void setTimer(int timer) {
      this.timer = timer
  }
}

因此假设A有3个对象,即a1,a2,a3

所有对象的elements的值将分别为10abcd,对吗?

是否可以更改它?(例如将 A 转换为 I)。但不可能创建具有不同 element 和 s 值的 A 对象..

请解释一下...

最佳答案

When I have a class that implements an interface , will all objects of that class have the same value of the members in the interface?

是的。实现接口(interface)的类将继承每个接口(interface)的成员。

All object's value of element and s will be 10 and abcd respectively right?

是的。

Is it possible to change it?

您无法更改 final 变量的值,但如果您希望 element (例如)在不同的上下文中保存不同的值,那么您可以隐藏它。例如,您可以引入另一个名为 element 的变量,它保存另一个值:

interface A {
    int x = 10;
}

class B implements A {
    static int x = 5;
    void test() {
        System.out.println(x);
    }
}

这里,B.x 变量隐藏A.x 常量。如果省略 int x = 5 声明,则 System.out.println(x) 将在 A 接口(interface)中打印常量。

关于Java - 接口(interface)成员的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32535502/

相关文章:

c# - 如何在接口(interface)中表示枚举?

java - 如何在 scriptlet 中使用 JSTL 变量?

java - 在Java中实例化游戏命令数组

java - 一对多、多对一和多对多之间的区别?

C++如何使类类型更通用并将其用作一种接口(interface)

java - 是否可以编写和加载您自己的核心 Java 类版本?

java - 如何在类实例和这些属性的其他可能用户之间共享属性?

interface - JRuby:带有 Ruby block 的 Java 命令模式:为什么它有效?

java - 什么是 android 中的 RoboSpice 库

inheritance - Go - 如何明确声明一个结构正在实现一个接口(interface)?