0

I try to learn about Aliasing and encounter this example:

public class A
{
    // Instance variable 
    private double _x;

    // 3 constructors 

    public A(double x)
    {
        _x = x;
    }

    public A()
    {
        _x = 0;
    }

    public A(A a)
    {
        _x = a._x;
    }

    // methods 
    public double getX()
    {
        return _x;
    }

    public void setX(double x)
    {
        _x = x;
    }

    public String toString()
    {
        return "A:" + _x;
    } 
}

static void Main(string[] args)
{
    A a1 = new A(7);
    A a2 = new A(a1);
    A a3 = a2;

    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    a1.setX(10);
    Console.WriteLine("after setting 10 to a1:");
    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    a3.setX(5);
    Console.WriteLine("after setting 5 to a3:");
    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    Console.ReadLine();
}

The first Console.WriteLine and the first SetX is clrea but why after a3.setX(5), also a2 changed ? According the declaration A a3 = a2 and SetX refer to a3

Zoe
  • 27,060
  • 21
  • 118
  • 148
user979033
  • 5,430
  • 7
  • 32
  • 50

1 Answers1

2

Both a2 and a3 are references¹ to the same object. Since you have one object (and two references to it), changing the object by means of any reference will produce changes visible, again, by means of any reference.


¹ Reference here is Java jargon for what in C/C++ is called pointer. And your example will show the same behaviour when you have pointer aliasing in those languages.

peppe
  • 21,934
  • 4
  • 55
  • 70
  • 1
    Technically there no pointers here. Consider changing the word "pointer" to "reference". – Rik Oct 30 '13 at 13:15
  • and why after set a1 to 10, a2 is still remained 7 ? – user979033 Oct 30 '13 at 13:54
  • Because `a1` is a reference to one object, and both `a2` and `a3` are references to *another* object. In total, you create two objects and three references, with `a2` and `a3` aliasing each other. What happens to the object referenced by `a1` is of course not visible through `a2` nor `a3`. – peppe Oct 30 '13 at 14:06