Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java class fields by reference?

I created the following test to see how Java handles objects and it's confusing me quite a bit.

public class MyClass
{
    public String text = "original";
    public MyClass(String text)
    {
        this.text = text;
    }
}

Then i created the following 2 scenarios:

1.

String object1 = new String("original");
String object2 = new String("original");
object2 = object1;
object2 = "changed";
System.out.println(object1);
System.out.println(object2);

Result:

original
changed

2.

MyClass object1 = new MyClass("object1");
MyClass object2 = new MyClass("object2");
object2 = object1;
object2.text = "changed";
System.out.println(object1.text);
System.out.println(object2.text);

Result:

changed
changed

Now why is the text field shared like a static field?

like image 313
John Frost Avatar asked Oct 19 '25 09:10

John Frost


2 Answers

Now why is the text field shared like a static field?

Look at this line:

object2 = object1;

That's setting the value of the object2 variable to be the same as the value of the object1 variable. Those variable values are both references to objects - they're not objects themselves.

So after that line, both variables have values referring to the same object. If you change the object via one variable, you'll still see that change via a the other variable. To put it in real world terms: suppose you have two slips of paper, each with your home address on, and give them to two different people. The first one goes and paints your front door red, then the second goes to visit your house - they will still see a red front doo.

It's very important to separate three concepts:

  • Objects
  • Variables
  • References

The value of a variable (or any other expression, actually) is always either a primitive value (int, char etc) or a reference. It's never a whole object.

Changing the value of one variable never changes the value of a different variable, so here:

String object1 = new String("original");
String object2 = new String("original");
object2 = object1;
object2 = "changed";

... we're changing the value of object2 once to have the same value as object1, and then to have a different value, referring to a String object with the text "changed". That never changes the value of object1.

Does that help? If not, please ask about very specific cases - it's easiest to pick several situations apart in detail rather than generalizing.

like image 95
Jon Skeet Avatar answered Oct 21 '25 21:10

Jon Skeet


Pictorial representation to explain this behavior

Step 1.

MyClass object1 = new MyClass("object1");
MyClass object2 = new MyClass("object2");

Step 2.

object2 = object1;

Step3.

object2.text = "changed";

enter image description here

like image 23
Kuldeep Jain Avatar answered Oct 21 '25 21:10

Kuldeep Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!