编程语言
首页 > 编程语言> > 是否有可能在Java中重载运算符?

是否有可能在Java中重载运算符?

作者:互联网

参见英文答案 > Operator overloading in Java                                    9个
我有以下类,它描述XY表面上的一个点:

class Point{
    double x;
    double y;

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

所以我想overlad和 – 操作符有可能写代码运行:

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)

我怎么能用Java做呢?或者我应该使用这样的方法:

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

提前致谢!

解决方法:

你不能用Java做到这一点.您必须在Point类中实现plus或add方法.

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

用法

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)

标签:java,operator-overloading
来源: https://codeday.me/bug/20191007/1868517.html