0

I am making a simple 2D physics engine as my first attempt at making any kind of physics engine. Unfortunately for anybody who's a fan of teaching physics, this is not a physics related question. I simply wanted to know if there was a way to define something simple like addition for a custom class. For example, I have created a class named Vector2D. If I have a velocity vector, and an acceleration vector, it would be easiest to simply have the following code:

Vector2D velocity = new Vector2D(xAxisVelocity, yAxisVelocity);
Vector2D acceleration = new Vector2D(xAxisAcceleration, yAxisAcceleration);
void update() {
    velocity += acceleration;
}

However, since velocity and acceleration are not primitive types, so I cannot just add them together. From what I know right now, I would have to add their components together like so:

velocity.x += acceleration.x

..and so on..

What I would like to know is: Is there a way to define addition for classes, similar to how toString() can be overridden?

Just to clear it up, it isn't that big of a deal for me to make a method for adding the two vectors together, I just want to know if overriding is possible.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • SO won't allow me to post my long answer since this question was marked as a duplicate. So please visit http://pastebin.com/AiHh7cBa to read my answer. – Emily Mabrey Jan 15 '16 at 22:38
  • 1
    @EmilyM You can always go post your answer on the linked duplicate. – azurefrog Jan 15 '16 at 22:44
  • @EmilyM Thanks for the answer, that's exactly what I've already done. –  Jan 15 '16 at 22:58

2 Answers2

1

No, there's no operator overloading in Java. It's a design choice and that's what we have to live with.

See Why doesn't Java offer operator overloading for more discussion.

Community
  • 1
  • 1
Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

No — there's no user-defined operator overloading in Java. (This is intentional; the language designers felt that this feature of C++ caused too many problems.)

ruakh
  • 175,680
  • 26
  • 273
  • 307