There is no operator overloading in Java as in C/C++ world, so the + operator is used, let's say only, for primitive numbers (byte
, short
, int
, long
, float
and double
) incremental operations.
This saying you should not complain or get surprised when you find a special case where the + operator is overloaded when it comes to the String
Class.
String s1 = "Hello ";
String s2 = "World";
String helloWorld = s1 + s2;
Look at the last line in above code, it is totally legal and will result on a concatenated String
and the compiler will never complain about it. Remember that this is the one and only exception.
So instead of overloading some operators, you can seamlessly implement a method that handles your addition stuff:
public class Complex
{
private double x;
private double y;
public Complex(double x , double y)
{
this.x = x;
this.y = y;
}
public Complex add (Complex c)
{
Complex sum = new Complex();
sum.x = this.x + c.x;
sum.y = this.y + c.y;
return sum;
}
}
public static void main(String args[])
{
Complex p1 = new Complex(1 , 2);
Complex p2 = new Complex(3 , 4);
Complex p3 = p2.add(p1);
}