简体   繁体   中英

How can i create a method that modifies an object of another class(java)?

I'd like to create a class that stores some events in the form of methods. When one of them is called i'd like to make it to take an object and to modify it, but if i'm not wrong the parameter of that method would be only a copy of the real object, so it wouldn't change anything about it. Is there a way to do it? I hope i have been clear enough...

Yes, you are right by saying that JAVA is pass by value and it will send a copy of that object but remember that in case of an object that copy will point to the same references as that of the original object.

Whatever you'll modify in the passed object will also get reflected in the original object. This is because the references are still same.

For Example,

public class Foo {
    private int x;

    /* Getter-Setter */
}

Now, consider following two objects:

Foo realObject = new Foo();
realObject.setX(1);

/* Call someMethod */
someMethod(Foo realObject);

/* someMethod Implementation */
public void someMethod(Foo copyObject) {
    copyObject.setX(5);
}

Now, the changes you did in copyObject will be reflected in realObject because internally it references the same location. Hence, the value of x in realObject will change from 1 to 5 .

The best way to achieve what you are trying to do is by using the copy constructor in your POJO class.

For Example,

public class Foo {
    private int x;

    public Foo(Foo f) {
        this.x = f.x;
    }
}

Now, you can copy the object as follows:

Foo realObject = new Foo();
realObject.setX(1);

/* Make Copy */
Foo copyObject = new Foo(realObject);
copyObject.setX(5);

This time changes to copyObject will not impact realObject . The value of x in realObject will still be 1 .

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