Reputation: 5668
i am working on a project that has an object called Vector2
public static class Vector2 {
public Vector2 (float x, float y) {
this.x = x;
this.y = y;
}
public float x;
public float y;
public static Vector2 ZERO = new Vector2 (0, 0);
public static Vector2 FORWARD = new Vector2 (0, 1);
public static Vector2 LEFT = new Vector2 (1, 0);
public static float Distance (Vector2 a, Vector2 b) {
return (float) Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}
}
and would like to do the following:
Vector2 a = new Vector2 (2.32, 453.12);
Vector2 b = new Vector2 (35.32, 532.32);
Vector2 c = a * b;
// c.x = 2.32*35.32
// c.y = 453.12*532.32
float num = 5;
c = a * num;
// c.x = 2.32*5
// c.y = 453.12*5
Is this possible? If so how can I do it, and what is it called? Thanks in advance.
Upvotes: 5
Views: 637
Reputation: 29867
What you are doing is called operator overloading. And while Java does not support it (Google to find a myriad of posts and opinions on the topic), some higher level languages that run on the JVM do, like Groovy. So if you are able to introduce Groovy into your project, you can accomplish this. Your Groovy code will compile down to the same JVM bytecode, so will be totally interoperable with your Java and can call existing Java in your project.
http://groovy.codehaus.org/Operator+Overloading
Upvotes: 1
Reputation: 4842
No, Java does not support operator overloading.
As an FYI: if it's possible for you to work with other languages, then C++ and, the very Java like, C# do support operator overloading. If your project, for example Ray Tracing, has a lot of vector related operations, then I'd actually consider a language like C#.
Upvotes: 5
Reputation: 10007
As Nadir said, it's called "operator overloading" and (for better or worse) it was not included in the Java specification. You can find it in C++ if you want to see it in action.
In Java, you'd need to add the following methods to your Vector2
class:
public Vector2 multiplyBy(Vector2 otherVector);
public Vector2 multiplyBy(float multiplier);
Upvotes: 1
Reputation: 12206
There is no operator overloading in Java. The best you can do is use a method.
public Vector2 multiply(Vector2 that){
return new Vector2(this.x * that.x, this.y * that.y);
}
Then if a
and b
are Vector2
objects you can do this
Vector2 c = a.multiply(b);
Upvotes: 4
Reputation: 1660
Java does not allow operator overloading like languages such as C++. See this article. Make utility functions to accommodate what you want to accomplish.
Upvotes: 4