Does Java support operator overload support?

I am working on a project that has a Vector2 object

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 it possible? If so, how can I do this and what is it called? Thanks in advance.

+5
source share
5 answers

No, Java does not support operator overloading.

Like FYI: if you manage to work with other languages, then C ++ and, in fact, similar to Java, C # supports operator overloading. If your project, like Ray Tracing, has a lot of vector operations, then I would really consider a language like C #.

+5
source

Java , , ++. . . , , .

+4

Java . , , .

public Vector2 multiply(Vector2 that){
    return new Vector2(this.x * that.x, this.y * that.y);
}

, a b Vector2,

Vector2 c = a.multiply(b);
+4

, " " ( ) Java. ++, .

Java Vector2:

public Vector2 multiplyBy(Vector2 otherVector);

public Vector2 multiplyBy(float multiplier);
+1

What you do is called operator overloading. And while Java does not support it (Google, to find a lot of posts and opinions on this topic), some higher-level languages ​​that work on the JVM, for example, Groovy. Therefore, if you can introduce Groovy into your project, you can do it. Your Groovy code will be compiled with a single JVM bytecode, so it is fully compatible with your Java and can invoke existing Java in your project.

http://groovy.codehaus.org/Operator+Overloading

+1
source

All Articles