Answer the question
In order to leave comments, you need to log in
How to pass an instance of the Long class by reference?
In the main method, I declare
further I pass it as a parameter to the constructor of another class, in which I assign a value to this objectLong l = 0l;
this.l = l;
this.l = 150l;
Answer the question
In order to leave comments, you need to log in
You are a little confusing ramsey God's gift and scrambled eggs changing an object by reference and changing a link. Specifically, in your case, you create a new object and assign a link to it.
Also, Long is immutable. Either way, you wouldn't be able to do anything.
If you really need to change the contents of a certain field in main from a class method, you will have to use self-written holders.
class Test {
public static void main(String[] args) {
LongHolder holder = new LongHolder(0L);
System.out.println(holder);
updateValue(holder, 150L);
System.out.println(holder);
}
private static void updateValue(LongHolder holder, Long newValue) {
holder.setValue(newValue);
}
private static class LongHolder{
private Long value;
public LongHolder(Long value) {
this.value = value;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
@Override
public String toString() {
return "LongHolder{" +
"value=" + value +
'}';
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question