我有超类test
和两个子类test1
和test2
。我认为,如果test1
更改test
中的字段,则test2
也会看到该更改。我的意思是
test1 n = new test1();
n.setX(5);
test2 a = new test2();
System.out.println(a.getX());
它返回0但我认为由于字段x
设置为5,因此在调用时会显示5。
你能澄清一下这种混乱吗?
答案 0 :(得分:2)
n
和a
是两个不同的实例。除非X
是static
字段,否则从一个实例设置它不应该影响另一个实例,无论它们是同一个超类的两个不同的子类。
答案 1 :(得分:2)
这不是继承和实例化的工作原理。
这与打印1
的事实没有什么不同test1 n1 = new test1();
test1 n2 = new test1();
n1.setX(1);
n2.setX(2);
System.out.println(n1.getX()); // prints 1
不同的实例具有自己的状态,即使它们具有相同的行为。对于超类型的子类型,这没有什么不同。创建后,所有实例都有自己的状态。
当然,静态字段(类变量)总是在所有子类型中共享。因此,在另一个子类型中可以看到对超级静态字段的更改。
public class MainApp {
public static void main(String[] args) {
Sub1 sub1 = new Sub1();
Sub2 sub2 = new Sub2();
sub1.setX(2);
System.out.println(sub2.getX()); // prints 2
}
}
class Super{
private static int X;
public int getX() { return X; }
public void setX(int x) { X = x; }
}
class Sub1 extends Super {}
class Sub2 extends Super {}
答案 2 :(得分:1)
假设setX
未修改静态变量,请考虑以下内容:
test n = new test1();
test a = new test2();
n
和a
是test
的单独实例,因此它们对超类的任何属性的所有修改都只针对它们自己的实例。任何子类实例都不共享超类的属性(除非它们是静态的)。
test n = new test1();
test a = n;
请注意new
声明中缺少a
限定词。现在a
和n
共享相同的实例,因此a
所做的任何修改都会影响n
,反之亦然。