0
public class TriVal {

private static int x;
private static int y;
private static int z;

TriVal(int x, int y, int z) {
    TriVal.x = x;
    TriVal.y = y;
    TriVal.z = z;

    }
 public int sum(TriVal p2) {
    int a = Math.abs(TriVal.x + p2.x);
    int b = Math.abs(TriVal.y + p2.y);
    int c = Math.abs(TriVal.z + p3.z);
    int sum = a + b + c;
    return sum;
    }
}

This is a piece of a constructor for an object that contains a set of 3 values. However, I am writing a function that creates a new TriVal made by summing the x, y, and z, of two instances of this object.

So say we have

    TriVal p1 = new TriVal(10, 10, 10);
    TriVal p2 = new TriVal(20, 20, 20);

calling the function

 p1.sum(p2)

(Which is included elsewhere in the class) should return 90. However, it returns 120. I am learning that upon creating a new instance of the TriVal Object, the previously defined p1 instance is somehow being set to the same values as p2, which explains the sum being 120. I believe this error is located somewhere in my constructor, perhaps in the way I am updating values or declaring variables at the top of the class? Any helpful tips would be appreciated, thank you!

rubyquartz
  • 319
  • 1
  • 2
  • 11
  • 1
    Do you know what the `static` keyword means? If you do not, I suggest looking it up. You are changing the static value x, not an instance variable x – Orin Mar 17 '17 at 16:47
  • Why are `x`, `y` and `z` declared to be `static`? That's your problem. – JonK Mar 17 '17 at 16:48
  • Possible duplicate of [What does the 'static' keyword do in a class?](http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class) – OH GOD SPIDERS Mar 17 '17 at 16:48

1 Answers1

0
private static int x;
private static int y;
private static int z;

You declared your instance member as static which will be same for all the instances. They store last assigned values. remove static and you'll be fine.

As @Orin pointed, you'll need to change the code a bit where you should bind your parameters to instance members.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • With his current code, you will also have to replace all instances of `TriVal.x` to `this.x`, etc. – Orin Mar 17 '17 at 16:48
  • Right, I noticed this earlier and attempted to remove static, however, I then get errors that I cannot make static references to a non-static field within the first constructor, which led me to believe I should keep the variables as static. – rubyquartz Mar 17 '17 at 16:50