Tristan Batchler
Tristan Batchler

Reputation: 223

How can I make two object variables refer to each other?

I am trying to create an alias for a object variable in Java so that I can change one and have it affect the other. For example, in this snippet, I expect "b" to be printed out. Instead I get "a".

String s = new String("a");
String t = s;
t = new String("b");
System.out.println(s);    // Prints "a".

I thought that non-primitive types in Java were able to be referenced and "tied" together like this.

Upvotes: 0

Views: 92

Answers (3)

Stefan
Stefan

Reputation: 2395

You might be looking for something like this:

StringWrapper sw = new StringWrapper(new String("a"));
StringWrapper tw = sw;
tw.setS(new String("b"));
System.out.println(sw.getS()); // Prints b

class StringWrapper {
    private String s;
    public StringWrapper(String s) {
        this.s = s;
    }
    private String getS() {
        return s;
    }
    private void setS(String s) {
        this.s = s;
    }
}

(You can replace new StringWrapper(new String("a")) with new StringWrapper("a"). I added new String so it looks more like your example. Same goes for new String("b").)

Upvotes: 0

fdreger
fdreger

Reputation: 12505

No, it never works like that. Variables, fields etc. cannot be "bound" in Java.

Your variables can contain "a link to a value" in a variable, but you cannot have a "link to another variable".

This means that in your case s and t initially hold the link to the same value, but they don't know about each other. When you assign a new string to t, the value of the old string does not change (and s still references the old value). It's just the reference in `t

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

String is not good example, because this is immutable. You have to look at using object instances and object reference. One object instance could have multiple object references.

class Decorator {
    private String str;

    public Decorator(String str) {
        this.str = str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public String getStr() {
        return str;
    }
}


Decorator s = new Decorator("a"); // s - is a reference to Decorator
System.out.println(s.getStr());  // prints "a"
Decorator t = s; // t - is an another reference to existed Decorator (two references for one instance)
t.setStr("b");
// references s and t both point to one Decorator instance
System.out.println(s.getStr());  // prints "b"
System.out.println(t.getStr());  // prints "b"

Upvotes: 0

Related Questions