I'm trying to figure out how to add two classes together with a simple arithmetic addition

The class i've written is a Vector3 class it looks like this

public class Vector3 {

public float x, y, z;

public Vector3(){
    x = 0.0f;
    y = 0.0f;
    z = 0.0f;

public Vector3(float _x, float _y, float _z){
    this.x = _x;
    this.y = _y;
    this.z = _z;
public Vector3 add(Vector3 other){
    Vector3 temp = new Vector3(this.x+other.x, this.y+other.y, this.z+other.z);
    return temp;


I have added the add method in order to be able to add vectors together temporarily. but i really want to be able to just type vectorA+vectorB instead of having to type vectorA.add(vectorB)

is there a way to do this. i know you can do it in python.

  • \$\begingroup\$ That's called operator overloading and has been addressed on Stack Overflow previously for Java. \$\endgroup\$ – Anko Sep 5 '15 at 21:28
  • \$\begingroup\$ If you like that, come to the dark side, C#! We have all the cool stuff for ages: lambdas, type inference, nonweird generics (debatable), operator overloads, extension methods, properties (no more getx, setx), "streaming operations" (LINQ), etc. \$\endgroup\$ – Kroltan Sep 6 '15 at 4:26
  • \$\begingroup\$ I wish I could use c#. But I'm studying software engineering. And we have to use java for the first two semesters :/ \$\endgroup\$ – Daniel Holst Sep 6 '15 at 6:07

To put it bluntly, you can't. Java does not allow the user to define operator overloads. You will have to continue to use the Vector3::add(Vector3) method that you have already created.

Java is Java, Python is Python (C++ is C++, and C is C); they are all different languages that do different things. You shouldn't expect one thing to work because it works in another language.


Java doesn't support operator overloading, but a similar language, C#, does. (C# and Java are very similar and are usually compared with each other)

The Unity engine, which uses C# scripting, already defines a Vector3 class, with several overloaded operators (including + and -).

There, you can do something like:

Vector3 result = new Vector3(1, 2, 3) + new Vector3(4, 5, 6);

Of course, if you cannot change your programming language (either by choice or because of the framework used), then this is not an option, and you should stick to using the add() method.


Not the answer you're looking for? Browse other questions tagged or ask your own question.