0

私が知っているように、あるオブジェクトが別のオブジェクトに割り当てられると (たとえば、o2 = o1)、o2 は o1 が指す実際のオブジェクトを指します。したがって、実際のオブジェクトの変更は両方のオブジェクトに表示されます。次のように、A1 と A2 という名前の 2 つのクラスがあるとします。

class A1{
    int a;  A2 a2;
    A1(int a, A2 a2) { 
        this.a = a; this.a2 = a2; }
    public void setA(int a) { this.a = a;}
    public void setA2(A2 a2) { this.a2 = a2;}
    public int getA() { return a;}
    public A2 getA2() { return a2;}
}

class A2 {
    int b;
    A2(int b) { this.b = b;}
    public void setB(int b) { this.b = b;}
    public int getB() { return b;}
}

メイン関数には次のものがあります。

A1 o1 = new A1(10, new A2(20));
A1 o2 = o1;
System.out.println("o2==="+o2.toString());
o1.setA(12);
o1.setA2(new A2(22));
System.out.println("o2==="+o2.toString());

結果は次のとおりです。

o2=(10,20)
o2=(12,22)

A1 o2 = o1 ステートメントにより、o2.a2 は o1.a2 を指します (それらは参照型です)。したがって、o1.setA2(new A2(22)) ステートメントを実行すると、o1.a2 の新しいオブジェクトが作成されますが、o2.a2 が指している前のオブジェクトは変更されません。したがって、2 番目の出力は (12,20) になるはずです。2 番目の出力が (12,20) ではなく (12,22) である理由を教えてください。

4

3 に答える 3

0

o2 は元の A1 オブジェクトを指しているため、この A1 オブジェクトに加えられた変更は o1 と o2 に表示されます。

A1 o1 = new A1(10, new A2(20)); //o1 points to a new A1 object
A1 o2 = o1; //o2 now points to the A1 object o1 points to
System.out.println("o2==="+o2.toString());
o1.setA(12); //setting the original A1 objects a to 12;
o1.setA2(new A2(22)); // setting the original A1 object's A2's b to 22.
System.out.println("o2==="+o2.toString());  // o2 still refers to the original A1 object so it will reflect the changes
于 2013-07-25T03:08:59.053 に答える