Kraken
Kraken

Reputation: 24233

Changing the value of an object in a method changes it globally?

Here's my Code

Class A

public class A {
    private int a;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}

Class Change

public class Change {
    public void changeSomething(A a){
        a.setA(13);
    }
}

Class Learn

public class Learn {
    public static  void main(String[] args) {
        A a = new A();
        Change change = new Change();
        change.changeSomething(a);
        System.out.println(a.getA());
    }
}

The output is 13. Now when i am passing an object to the changeSomething method, internally the value of Object A has been changed but why do i see this effect outside that function?

Is not this equivalent to passing by value in C where unless you return that variable/Object you dont get the updated value.

i.e. dont i need to do a=changeSomething(a); and set the return type of this method to be as A?

Thanks

Upvotes: 0

Views: 539

Answers (4)

This is because you pass the Object, and objects in Java are always passed by reference. Only primitive (int, double, char, long...) are passed by value.

In C it could be:

public void changeSomething(A& a){
 a.setA(13);
}

Upvotes: -3

Brian Agnew
Brian Agnew

Reputation: 272357

You're passing a reference to the original object around. When you write a method

void someMethod(A param) { ... }

param is a reference to the original object. The original object isn't being copied. Consequently when you change this object, the change is visible wherever that object is observed.

When you write:

private A a = new A();

it's important to realise that the variable is a reference to object type A, not an actual object type A. It's a fine distinction, granted.

The above behaviour can cause unexpected effects across your system, and it's an argument for immutability, especially in threaded environments where changes can be triggered from multiple threads.

Upvotes: 2

Scorpio
Scorpio

Reputation: 2327

Well the code you provided works directly on an instance of A. This instance is changed, no matter if you return it or not. Its still the same instance of your object. And this instances variable reflects the new value.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240948

Short:

changeSomething() will update the value for object so if you refer to same instance you will get the same value back

Bit long explanation:

//an Object of A created and its reference is set to a
A a = new A();
//instance of Change is created and its reference is set to change
Change change = new Change();
//it passes reference's (a) 's value to the changeSomething method
//which invokes `setA()` on instance referred by a (which is the same instance that waas crated in line 1

change.changeSomething(a);

//so you will get the changed value here
System.out.println(a.getA());

Upvotes: 1

Related Questions