How to overload operators +, -, /, *, == for your own types?

  • Java does not support operator overloading - Alexey Shimansky
  • What a strange war of edits? Correcting typos, do you like to roll back to the wrong options? - AK
  • 2
    You do not think that your question is needed by someone other than you - they asked, received an answer, and then at least the grass does not burn. And there are people who ask a question on the Internet and get on the questions already asked by someone earlier. Therefore, the spelling is quite important, I hope that this is more understandable to you now. And do not see around karmofermers, the world is much more diverse. - AK

1 answer 1

No Java does not support operator overloading.

You can implement your own type arithmetic using class methods.

A simple example:

 public class MyObject { private int mX; private int mY; public MyObject(int x, int y) { mX = x; mY = y; } public int getX() { return mX; } public int getY() { return mY; } @Override public String toString() { return "[" + mX + ", " + mY + "]"; } public static MyObject multiply(MyObject firstObject, MyObject secondObject) { int x = firstObject.getX()*secondObject.getX(); int y = firstObject.getY()*secondObject.getY(); return new MyObject(x, y); } } 

 MyObject firstObject = new MyObject(2,5); MyObject secondObject = new MyObject(3,8); MyObject result = MyObject.multiply(firstObject, secondObject); System.out.println(firstObject + " * " + secondObject + " = " + result); 

Conclusion:

 [2, 5] * [3, 8] = [6, 40] 

Also, the multiply(...) method can be made non-static and manipulated with this and one transmitted object. Then the multiply(...) method can be called like this:

 firstObject.multiply(secondObject); 
  • How then to implement the arithmetic of its own types in principle? - user229157 2:55
  • @ user229157, Using class methods. - post_zeew Nov.
  • Type this x.add(y) ? - user229157 2:57
  • @ user229157, Yes. - post_zeew Nov. 2:58
  • Krustyak Spasibon - user229157