I'm having trouble understanding how object references work in Java?

Elmer :

The way I understood references originally was that they were simply memory references that held the memory location of the actual object they hold. The code below and its output confuses that for me, though. Here you can see the implementation of a simple class Man.

I create a Man object in the first line with the reference being called peter. peter on its own is just a memory location, right? So person should just be storing the object in the memory location it is at.

But when I assign another Man reference to peter and later change peter's name, person does not know this and prints the first name. How can this be since it stores the memory reference for peter? Shouldn't it be able to follow changes made to it?

public class Testing {

  public static void main(String[] args) {
    Man peter = new Man("brown", 182, 78000, "Peter");
    Man person = peter;
    peter = new Man("brown", 182, 78000, "Leonard");
    System.out.println(person.name);
  }
}

class Man {

   String hairColor;
   int height;
   double salary;
   String name;

   public Man()
   {
     hairColor = "brown";
     height = 180;
     salary = 50500.5;
     name = "John";
   }
   public Man(String hair, int high, double pay, String nam)
   {
        this.height = high;
        this.hairColor = hair;
        this.salary = pay;
        this.name = nam;
   }
}
GhostCat salutes Monica C. :

Here:

Man peter = new Man("brown", 182, 78000, "Peter");

creates a Man object named "Peter".

Man person = peter;

creates another variable "pointing" to the object created above.

peter = new Man("brown", 182, 78000, "Leonard");

creates another Man named Leonard, and afterwards the peter variable "points" to that new, second object.

Note: person didn't "point" to peter. It points to the Man "object" in memory.

And putting another "memory address" into the peter variable doesn't change the initial object you created.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325196&siteId=1