Home > Mobile >  Java - Can I multiply referenced values?
Java - Can I multiply referenced values?

Time:03-02

If I have a class as follows, just to store a value:

public class RefTest{
    private int value;

    public void setValue(int value){
        this.value = value;
    }

   public int getValue(){
        return value;
    }
}

and want RefTest b to always be double RefTest a, how would I go about it? Currently I have the values equal:

RefTest a = new RefTest();
a.setValue(5);
RefTest b = new RefTest();
b = a;
System.out.println("RefTest a: " a.getValue());
System.out.println("RefTest b: " b.getValue());
a.setValue(10);
System.out.println("RefTest a: " a.getValue());
System.out.println("RefTest b: " b.getValue());

But I'm not sure how to go about setting b to 2a, as "b=2a" returns an error(as expected), and b.setValue(2*a.getValue()) doesn't update when a.setValue() changes.

CodePudding user response:

What you're looking to accomplish can't be done the way you've implemented RefTest

The fact you want a and b to behave differently means they can't really be the same RefTest object.

While the requirement is a bit odd, from a reference perspective you need to actually store a reference to the object (a in this case) instead of the int value which is not a reference (that value is computed and set at the time you call setValue). You'll still need to do other work to actually ensure your getValue is always two times whatever value a is.

You'll need to actually define two separate objects, where the behaviour of 'b' would be the variable (which can be a reference to another object) if it has an intValue be two times that value

If you're new to Java please look into differences between int and an object reference in instance variables, and also patterns like composition (which could help you in this scenario)

CodePudding user response:

Taking your definition of RefTest as given, define another class like:

public class RefTestMultiple{
   private RefTest source;
   private int multiplier;

   RefTestMultiple(RefTest source, int multiplier) {
      this.source = source;
      this.multiplier = multiplier;
   }    

   public int getValue() {
        return multiplier * source.getValue();
   }

You can use it like this:

RefTest a = new RefTest();
RefTestMultiple b = new RefTestMultiple(a,2);
a.setValue(5);
System.out.println(b.getValue());

CodePudding user response:

I don't think b = a is doing what you think it is doing. What you want instead is:

b.setValue(a.getValue());

And for b = 2a what you want is:

b.setValue(2 * a.getValue());

Indeed the value of b will not update when the value of a changes. This is not math, these are procedural expressions.

  • Related