-1
public class Main{
.
.
.
Class class = new Class();
class.method(class.variableFromAnotherClass);
sysout(class.variableFromAnotherClass)
}

public class Class{
Int variableFromAnotherClass=0;

method(int var){
    var=1;
    }
}

Output:

0

Im dealing with a situation similar to the one above except with more variables in my version of "Class". My issue is that the method within "Class" does nothing to the variable being passed through. Why does this happen? Is it because the variable being passed through already belongs to the class? Any suggestions on What should I do to solve this problem?

David Veloso
  • 33
  • 1
  • 1
  • 4

3 Answers3

0

please make both the method and the variable static

public class Class{
static Int variableFromAnotherClass=0;

static method(int var){
    var=1;
    }
}
suulisin
  • 1,414
  • 1
  • 10
  • 17
0

Try java getters and setter and make instance variables of another class private which will add encapsulation.

0

The problem you are facing has to do with Java passing variables by reference, instead of by value. when variableFromAnotherClass is passed into class.method(int var), the int var variable is created from a copy of variableFromAnotherClass. so when var=1 is called, it updates the copy of variableFromAnotherClass, and not variableFromAnotherClass itself.

If you want to be able to change variableFromAnotherClass from Main, you can write class.variableFromAnotherClass=1; instead of calling method.

Another, more professional way of updating variables is using getters and setters:

public class Class {

    int variableFromAnotherClass;

    public void getVar() {
        return variableFromAnotherClass;
    }

    public int setVar(int var) {
        this.variableFromAnotherClass = var;
    }

}
  • Downvoted as this is misleading. Java is very much pass by _value_, it's just that for non-primitive types that value _is_ a reference. I suspect the duplicate question's answer can put this much better than I can. – BeUndead Mar 17 '20 at 11:25