Java class fields by reference?

I created the following tests to understand how Java handles objects, which puzzled me

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

Then I created the following two scenarios:

one

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

two

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 are text fields shared like static fields?

Solution

Look at this line:

object2 = object1;

This sets the value of the object2 variable to be the same as the value of the object1 variable These variable values are references to objects - they are not objects themselves

Therefore, after this line, both variables have values that refer to the same object If you change an object through one variable, you will still see the change through another variable In real world terms: suppose you have two pieces of paper, each with your home address, and give them to two different people First go to your front door and paint it red, then the second go to see your house - they will still see a red front door

It is important to separate the three concepts:

>Objects > variables > references

The value of a variable (or any other expression, in fact) is always the original value (int, char, etc.) or reference It is never a complete object

Changing the value of one variable will never change the value of another variable, so here:

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

... we change the value of object2 to have the same value as object1, and then use a different value to refer to a string object with "changed" text This will never change the value of object1

Does this help? If not, ask for a very specific situation - the simplest choice is details rather than generalizations

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>