此克隆示例让我困惑。我不明白前两个输出可以如何:111和222,而不是:222和222. 这不是“a2 =(A)a1.clone();”意味着a2和a1一样吗?Java克隆继承示例
代码:
public class Main {
public static void main(String[] args) {
A a1 = new A();
A a2;
B b1 = new B();
B b2;
a2 = (A) a1.clone();
a2.setI(222);
// Why the different output?
System.out.println("a1 = " + a1 + " a1.i " + a1.getI()); // i = 111
System.out.println("a2 = " + a2 + " a2.i " + a2.getI()); // i = 222
b2 = (B) b1.clone();
b2.setI(888);
b2.setJ(999);
System.out.println("b1 = " + b1 + " b1.i " + b1.getI() + " b1.j " + b1.getJ());
System.out.println("b2 = " + b2 + " b2.i " + b2.getI() + " b2.j " + b2.getJ());
}
}
public class A implements Cloneable {
private int i = 111;
@Override
public Object clone() {
try {
A a = (A) super.clone();
return a;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
public class B extends A {
private int j = 222;
@Override
public Object clone() {
Object o = super.clone();
B b = (B) o;
return b;
}
public int getJ() {
return j;
}
public void setJ(int j) {
this.j = j;
}
}