Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

References objects in Java [duplicate]

I have a doubt about object references in Java. It always send its object by reference to the functions, and it means that if you modifie them in the function sent, they will come back modified.

A solution for this would be copying the object before the send. But for that, do I have to create a copy function in the object class? Or is any other alternative? Thanks

like image 912
Frion3L Avatar asked Nov 29 '25 23:11

Frion3L


2 Answers

I typically add a copy constructor for this kind of scenario like so:

public class MyObject {
    //members


    public MyObject(MyObject objectToCopy) {
       this.member = objectToCopy.member;
       //...
    }
}

Then you can just make a new object with a simple one liner.

public void DoWork(MyObject object) {
    MyObject copy = new MyObject(object);
    //do stuff
}
like image 56
Matthew Cox Avatar answered Dec 02 '25 14:12

Matthew Cox


Java is always pass-by-value. What you are describing is passing the object reference by value.

There is a key distinction here. You are not passing the object as a reference, so the reference link is broken as soon as you assign a new instance to your parameter. As long as the reference value remains the same, altering the contents of an object passed in will persist when you return back to the caller. Another key difference is that a reference value can be null... but null is not an object - so how can you reference the absence of an object?

If you want to create a new object, you will need to copy the existing one. The copy should be performed inside the method to ensure the operation is consistent.

For simple objects (objects with a shallow class hierarchy, like the example below), you can usually get by with a basic copy constructor:

class Album {
  private String title;
  private String artist;

  public Album(Album copy) {
    this.title = copy.title;
    this.artist = copy.artist;  
  }
}

This will allow you to copy the object inside your method:

public void copyAlbum(Album album) {
    album = new Album(album); // Clone the album passed in
}

For more complex object graphs, you may want to use a library such as Orika or Dozer to accurately create a deep copy of your object. This question has some useful advice on copying objects in Java.

like image 39
seanhodges Avatar answered Dec 02 '25 13:12

seanhodges



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!