classC代码:
package jichu; public class ClassC { private int s1; private int s2; public ClassC(int s1, int s2) { this.s1 = s1; this.s2 = s2; } public ClassC(ClassC c) { this.s1 = c.s1; this.s2 = c.s2; c.s1++; c.s2++; } public String toString() { return "s1:" + s1 + ";s2:" + s2; } }
调用:
package jichu; public class MainClass { public static void main(String[] args) { ClassC c1 = new ClassC(1, 2); ClassC c2 = new ClassC(c1); System.out.println(c1); System.out.println(c2); } }
打印:
s1:2;s2:3
s1:1;s2:2
以相同类型的一个对象初始化另一个对象时,因为在类中,所以可以直接访问私有的成员变量。
public ClassC(ClassC c) { this.s1 = c.s1; this.s2 = c.s2; c.s1++; c.s2++; }