operator overloading - Define += for custom classes in Java -
this question has answer here:
- operator overloading in java 9 answers
i making simple 2d physics engine first attempt @ making kind of physics engine. unfortunately who's fan of teaching physics, not physics related question. wanted know if there way define simple addition custom class. example, have created class named vector2d. if have velocity vector, , acceleration vector, easiest have following code:
vector2d velocity = new vector2d(xaxisvelocity, yaxisvelocity); vector2d acceleration = new vector2d(xaxisacceleration, yaxisacceleration); void update() { velocity += acceleration; }
however, since velocity , acceleration not primitive types, cannot add them together. know right now, have add components so:
velocity.x += acceleration.x
..and on..
what know is: there way define addition classes, similar how tostring()
can overridden?
just clear up, isn't big of deal me make method adding 2 vectors together, want know if overriding possible.
no, there's no operator overloading in java. it's design choice , that's have live with.
see why doesn't java offer operator overloading more discussion.
Comments
Post a Comment