This class ds
has two fields, x and y
public class ds
{
private int x;
private int y;
public ds(int xx, int yy)
{
x = xx;
y = yy;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int xx)
{
x = xx;
}
public void setY(int yy)
{
y = yy;
}
}
This class ptrs
uses ds
to print results. I note that the printouts are the same whether int
or Integer
is used in ds
.
public class ptrs
{
public static void main(String[] args)
{
ds d = new ds(1,2);
System.out.println("d.x:" + d.getX()); //1
System.out.println("d.y:" + d.getY()); //2
//t is an object reference (a pointer) which points to d, which in turn
points to the ds object
ds t = d;
System.out.println("t.x:" + t.getX()); //1
System.out.println("t.y:" + t.getY()); //2
t.setX(3);
t.setY(4);
System.out.println("");
System.out.println("t.x:" + t.getX()); //3
System.out.println("t.x:" + t.getY()); //4
System.out.println("d.x:" + d.getX()); //3
System.out.println("d.y:" + d.getY()); //4
d.setX(5);
d.setY(6);
System.out.println("");
System.out.println("d.x:" + d.getX()); //5
System.out.println("d.x:" + d.getY()); //6
System.out.println("t.x:" + t.getX()); //5
System.out.println("t.x:" + t.getY()); //6
}
}
When I call the set methods on either d
or t
, calling the get methods on either pointer results in the updated values. Why is there apparently different behavior in the next example?
public class main
{
public static void main(String[] args)
{
Integer i = new Integer(5);
Integer a = i;
System.out.println("i is " + i ); //5
System.out.println("a is " + a ); //5
i = new Integer(10);
System.out.println("i is " + i ); //10
System.out.println("a is " + a ); //5
}
}
If I set an Integer object reference i
to point to an Integer object with value 5, and then make another reference a
refer to i
, why does a
still point to 5 even after I make i
reference another Integer object with value 10?
Is the difference because in the first example I change fields of the same object, but in the second example I point to a new object? But why would that cause a difference, if that is the reason..?