简体   繁体   中英

Assigning values to java object

I have the following code:

Color3D pixel = new Color3D(200, 0, 0);  
Color3D temporal  = pixel;  
System.out.println(util.printColor("Pixel: ", pixel));  
System.out.println(util.printColor("Temporal: ", temporal));  
pixel.setR(0);  
pixel.setG(200);  
pixel.setB(0);  
System.out.println(util.printColor("Pixel: ", pixel));  
System.out.println(util.printColor("Temporal: ", temporal));  

Result:

Pixel: r: 200, g: 0, b: 0  
Temporal: r: 200, g: 0, b: 0  
Pixel: r: 0, g: 200, b: 0  
Temporal: r: 0, g: 200, b: 0  

My class Color3D saves RGB (int)values.
I use the object util to print the int values of a Color3D object.

If you look at the result, for some reason after changing the red and green values of the pixel object I'm also modifying the green's values and I don't want that behaviour.

I want to have:

Pixel: r: 200, g: 0, b: 0  
Temporal: r: 200, g: 0, b: 0  
Pixel: r: 0, g: 200, b: 0  
Temporal: r: 200, g: 0, b: 0  

The object temporal was created with the intention of saving the pixel object values for a future process. The object temporal will also change in future...

You're assigning references not objects.

// Create new Color3D object, and put reference in pixel reference variable
Color3D pixel = new Color3D(200, 0, 0); 
// Copy reference from pixel reference variable to temporal reference variable
Color3D temporal  = pixel;

You now have two reference variables holding equal references to the same object. Thus, any modifications are visible through both variables. You presumably want something like:

Color3D temporal  = new Color3D(pixel.getR(), pixel.getB(), pixel.getB());

I don't know if those are real methods, but you should see the idea. Note that this creates a new, independent object.

With this code:

Color3D pixel = new Color3D(200, 0, 0);  
Color3D temporal  = pixel;  

you've only created one Color3D object. Objects are only created whenever new is called.

temporal is a reference to the same object that pixel refers to. Invoking methods on temporal is the same thing as invoking methods on pixel .

If you want each variable to refer to a different object with the same value, then you need to actually create two different objects:

Color3D pixel = new Color3D(200, 0, 0);  
Color3D temporal = new Color3D(200, 0, 0);  

Your temporal and pixel points to the same memory. So if you change one other one will pick up the change as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM