Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload operators in Java? [duplicate]

I have the following class, which describe one point on XY surface:

class Point{
    double x;
    double y;

    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }
}

So I want to overlad + and - operators to have possibility write run following code:

Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)

How can I do it in Java? Or I should use methods like this:

public Point Add(Point p1, Point p2){
    return new Point(p1.x + p2.x, p1.y + p2.y);
}

Thanks in advance!

like image 837
Dmitry Belaventsev Avatar asked Dec 04 '11 12:12

Dmitry Belaventsev


People also ask

Can we overload operator twice?

No this is not possible. The compiler can't know which version you want, it deducts it from the parameters. You can overload many times, but not by the return type.

Which operator we Cannot overload in Java?

Example 5: Overloading this .(dot) operatorDot (.) operator can't be overloaded, so it will generate an error.

Which operator in Java can be overloaded?

+ and += are overloaded for String objects. There are many other examples of operator overloading in Java.

Is it possible to overload operator?

These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.


3 Answers

You cannot do this in Java. You'd have to implement a plus or add method in your Point class.

class Point{     public double x;     public double y;      public Point(int x, int y){         this.x = x;         this.y = y;     }      public Point add(Point other){         this.x += other.x;         this.y += other.y;         return this;     } } 

usage

Point a = new Point(1,1); Point b = new Point(2,2); a.add(b);  //=> (3,3)  // because method returns point, you can chain `add` calls // e.g., a.add(b).add(c) 
like image 145
maček Avatar answered Nov 13 '22 18:11

maček


Despite you can't do it in pure java you can do it using java-oo compiler plugin. You need to write add method for + operator:

public Point add(Point other){
   return new Point(this.x + other.x, this.y + other.y);
}

and java-oo plugin just desugar operators to these method calls.

like image 20
mart Avatar answered Nov 13 '22 17:11

mart


There is no operator overloading in Java. Apparently for reasons of taste. Pity really.

(Some people will claim that Java does have overloading, because of + with String and perhaps autoboxing/unboxing.)

Let's talk about value types.

Many early classes (and some later ones) make a right mess of this. Particularly in AWT. In AWT you should be explicitly making copies of simple values all over the place. Almost certainly you want to make value types immutable - the class should be final and it should never change state (generally all final fields pointing to effective immutables).

So:

public final class Point {
    private final int x;
    private final int y;

    private Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public static of(int x, int y) {
        return new Point(x, y);
    }

    public int x() {
        return x;
    }
    public int y() {
        return y;
    }
    public Point add(Point other) {
        return of(x+other.x, y+other.y);
    }

    // Standard fluffy bits:
    @Override public int hashCode() {
        return x + 37*y;
    }
    @Override public boolean equals(Object obj) {
        if (!(obj instanceof Point)) {
            return false;
        }
        Point other = (Point)obj;
        return x==other.x && y==other.y;
    }
    @Override public String toString() {
        return "("+x+", "+y+")";
    }
}

The original code was confused between int and double, so I've chosen one. If you used double you should exclude NaN. "Point" tends to imply an absolute point, which doesn't make sense to add. "Vector" or "dimension" would probably be more appropriate, depending upon what you intend.

I've hidden the constructor, as identity is not important. Possibly values could be cached. Possibly it is, say, common to add a point to a zero point, so no points need to be created.

It's possible you might want a mutable version, for example to use as an accumulator. This should be a separate class without an inheritance relationship. Probably not in simple cases, but I'll show it anyway:

public final class PointBuilder {
    private int x;
    private int y;

    public PointBuilder() {
    }
    public PointBuilder(Point point) {
        this.x = point.x;
        this.y = point.y;
    }
    public Point toPoint() {
        return new Point(x, y);
    }

    public PointBuilder x(int x) {
        this.x = x;
        return this;
    }
    public PointBuilder y(int y) {
        this.y = y;
        return this;
    }
    public PointBuilder add(Point other) {
        this.x += other.x;
        this.y += other.y;
        return this;
    }
}
like image 30
Tom Hawtin - tackline Avatar answered Nov 13 '22 17:11

Tom Hawtin - tackline