문제

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

도움이 되었습니까?

해결책 3

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); 
}

다른 팁

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.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top