What is the method for assigning values to Java objects?
There are two methods of assigning values to Java objects.
- Direct assignment: By using the equal sign (=) to assign one object to another, the reference of the source object is copied to the target object, causing both objects to point to the same memory address. This means that any modifications made to the target object will also affect the source object.
For example,
Object obj1 = new Object();
Object obj2 = obj1; // 将obj1的引用赋值给obj2
- Creating new objects using constructors or factory methods: by invoking the constructor or factory method of the target object and using the property values of the source object, a new object is created. This process generates a new object, copies the property values from the source object to the new object, and results in the new object pointing to a different memory address than the source object.
For example:
class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
// 省略其他代码
}
MyClass obj1 = new MyClass(10);
MyClass obj2 = new MyClass(obj1.getValue()); // 使用obj1的属性值创建一个新的MyClass对象
These two assignment methods serve different purposes in different scenarios. Direct assignment is suitable for copying object references, while using constructors or factory methods is ideal for creating new objects and initializing their attribute values.