2

Consider the class

public class Complex 
{
    private double x;
    private double y;

    public Complex(double x , double y)
    {
        this.x = x;
        this.y = y;
    }
}

That represents a Complex number x + y*i , where i is the imaginary part.

I have the following main :

public static void main(String args[])
{
    Complex p1 = new Complex(1 , 2);   // ok 
    Complex p2 = new Complex(3 , 4);   // ok 
    Complex p3 = p1 + p2;   // Not ok , doesn't compile 
} 

The third line Complex p3 = p1 + p2; doesn't compile , since there is no operator overloading in Java . It would have worked in C++ .

Any way around this (in Java) ?

Much appreciated

user2864740
  • 60,010
  • 15
  • 145
  • 220
JAN
  • 21,236
  • 66
  • 181
  • 318

3 Answers3

4

Operator overloading is not possible in Java. What you have to do instead is to implement methods for the operations.

BigDecimal is a good example of how this should be done in Java:

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

note that BigDecimal is a immutable class, this is often a very good idea when you have classes that you in C++ would have operator overload like this for. It makes for cleaner code that is easy to maintain.

Vegard
  • 1,802
  • 2
  • 21
  • 34
3

Not really no. Operator overloading is not supported in Java for various reasons. You can just provide an add method or something similar.

nils
  • 1,362
  • 1
  • 8
  • 15
1

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); 
}
tmarwen
  • 15,750
  • 5
  • 43
  • 62