1

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.

SchoolJava101
  • 609
  • 1
  • 5
  • 8

2 Answers2

2

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 "*").

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Ah that's slightly disappointing, but thanks for the explanation! Guess I'll just have to do it like a savage animal... – SchoolJava101 Sep 19 '16 at 16:40
  • Thats the thing with life: things are as they are; not as we wish them to be! Still glad that I could help. – GhostCat Sep 19 '16 at 16:42
1

Simply put: You can't.

Java does not support operand overloading. There are other languages that build on the JVM (groovy, kotlin and scala) that support it - but ultimately they're doing the same as your second example.

In detail: The Java Spec sheet does not account for any operator overloading (for example, here: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17)

Mio Bambino
  • 544
  • 3
  • 15