Ivan Ehreshi
Ivan Ehreshi

Reputation: 77

Java working with references

The title a little bit disappointing but I cannot figure out how to properly formulate the question. So, I show my problem on the code. For example we have:

public class Test {

    public Value  val;

    Test(Value val){
        this.val = val;
    }

    public static void main(String[] a){
        Value val = new Value(1);

        Test test1 = new Test(val);
        val = new Value(2);

        System.out.println(test1.val.val);
    }
}

How can I change my code easily to let test1 point to the new Val (that that have the value of 2). Suppose the we need to have such references(to the actual variable and not the memory) all over the program

UPD: One of the solution I found is to make a "update" method. So I could write val.update(new Val(2))

UPD: I totally agree with the setter methods. What I want is not OOP style, but in my project I need a rapid solution even if it would not be the best. I think I found one solution(it is actually bad but faster then writing setters and getters. The solution is to create a "wrapper" class(I could name it "Reference")

Upvotes: 0

Views: 93

Answers (2)

ReneS
ReneS

Reputation: 3545

Because we are supposed to give answers, I just will repeat what we got in the comments already.

To change the value of your instance variable Value val from the outside of the class, you have to write setter methods. If you want to retrieve the value, you need getter methods.

Bad practice: You should not declare the instance variable public and directly write it. This goes against OOP principles such as encapsulation aka you do not want to know what is done in the class, you just want to know its external behavior. So declare it private.

Also check Use public getters/setters to access private variables in the same class, or access the variables directly and http://www.cs.colostate.edu/~cs161/Fall12/labs/lab2/bookgetset.html

Upvotes: 1

Makoto
Makoto

Reputation: 106518

Normally, you want to define a setter to change any of your field values in a class.

public void setVal(Value val) {
    this.val = val;
}

But, since your val field is public, you don't have to use a setter at all.

// after you've declared `val` to be a new value
test1.val = val;

Setters are the convention when dealing with JavaBeans, or with frameworks that have an expectation that a field has a corresponding getter and/or setter.

Upvotes: 3

Related Questions