Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java support operator overloading?

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.

like image 468
Patrick Lorio Avatar asked Jan 17 '12 01:01

Patrick Lorio


People also ask

Why Java does not support method overloading?

As said in previous answers, java does not support method overloading with different return type and same arguments. This is because, it has to determine which method to use at the compile time itself. To remove the ambiguity, they designed the method overloading technique like this.

What is meant by operator overloading in Java?

Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed.

Which feature is not support in Java?

Explanation: The Java language does not support pointers; some of the major reasons are listed below: One of the major factors of not using pointers in Java is security concerns. Due to pointers, most of the users consider C-language very confusing and complex.


2 Answers

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#.

like image 192
Nadir Muzaffar Avatar answered Sep 28 '22 02:09

Nadir Muzaffar


Java does not allow operator overloading like languages such as C++. See this article. Make utility functions to accommodate what you want to accomplish.

like image 41
xikkub Avatar answered Sep 28 '22 04:09

xikkub