当我有一个实现接口(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
所有对象的element
和s
的值将分别为10
和abcd
,对吗?
是否可以更改它?(例如将 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/