1

I've got a simple class called Vector2 which is pretty much:

class Vector2 {
    public int x, y;
    public Vector2(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

With some methods, etc. I'd like to be able to do:

Vector2 myVector = new Vector2(2, 1);
myVector *= 2;

and myVector would be (4, 2).

Is this possible? What would I need to add to my class?

Firedan1176
  • 641
  • 3
  • 8
  • 18

1 Answers1

4
Vector2 myVector = new Vector2(2, 1);
myVector *= 2;

Is this possible?

No. Not in Java. Other languages like C++ support that. Called Operator overloading because you redefine what the *-operator does.

In Java you have to use explicit methods. Like

myVector.multiplyBy( 2 )

and it would look like

class Vector2 {
    public int x, y;
    public Vector2(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public void multiplyBy(int value) {
        this.x *= value;
        this.y *= value;
    }
}

or like

    public Vector2 multiplyBy(int value) {
        return new Vector2(this.x * value, this.y * value);
    }

And then you would do

Vector2 myMultipliedVector = myVector.multiplyBy( 2 );

with the advantage that you don't modify the original object but create a new one with a different value.


Groovy (language that is derived from Java & runs on the JVM) takes that idea and actually allows you to write someObject *= 2 as long as you provide a method that must be called multiply. Maybe one day that makes it into Java. Maybe not. But basically all legal Java code is also legal Groovy code so you could do it right now, in a program that looks like Java and runs in the Java VM.

Community
  • 1
  • 1
zapl
  • 63,179
  • 10
  • 123
  • 154