javac#multiplicationoperand

Java - Add Support in a Class to Allow Multiplying


In programs such as Unity3D that have Vector2/Vector3's etc (I use C# coding in the program), you can multiply Unity's Vector objects by a float simply using the '*' operand and no explicit methods. Eg:

Vector2 oldVector = new Vector2(10f, 10f);
Vector2 newVector = oldVector * -2f

And then newVector would have the value (-20f, -20f).

As opposed to something using methods like:

Vector2 oldVector = new Vector2(10f, 10f);
Vector2 newVector = oldVector.multiply(-2f);

Basically how would you tell Java to handle this/implement it into your class? Is there even a way?

I realise this may just be convoluted and that it's likely significantly easier to just use methods, but I feel like it would be interesting to learn and maybe useful at a later stage.


Solution

  • Very simple: Java doesn't allow for operator overloading; which is the concept behind "hiding" a method call that way.

    You see, in essence, that code is dealing with object/reference types in the end. So even when other languages allow you to write "*" instead of "multiply"; in the end, there is still a method that gets invoked.

    Basically that was a decision made on purpose when Java was put in place. Many people disliked operator overloading (pointing at C++ where such things were often misused); so the argument was made that Java should not allow for it.

    If your main concern is to use * instead of multiply; there are plenty of other languages that run on the JVM (Scala for example) that give you operator overloading (but to be honest: Scala doesn't have operator overloading, but it allows you to name your method "*").