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

Dmi*_*sev 17 java operator-overloading

我有以下类,它描述XY表面上的一个点:

class Point{
    double x;
    double y;

    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我想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)
Run Code Online (Sandbox Code Playgroud)

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

public Point Add(Point p1, Point p2){
    return new Point(p1.x + p2.x, p1.y + p2.y);
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

mač*_*ček 11

你不能用Java做到这一点.您必须在班级中实施plusadd方法Point.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

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)
Run Code Online (Sandbox Code Playgroud)

  • 讨厌 Java 的另一个原因:( (2认同)

mar*_*art 8

尽管你不能在纯java中做到这一点,你可以使用java-oo编译器插件来做到这一点.你需要为+运算符编写add方法:

public Point add(Point other){
   return new Point(this.x + other.x, this.y + other.y);
}
Run Code Online (Sandbox Code Playgroud)

和java-oo插件只是desugar运算符到这些方法调用.

  • 当然,这是一个愚蠢的想法,除非只有你会阅读你的代码 (2认同)

M S*_*M S 2

在 Java 中无法执行此操作,因为 Java 中没有运算符重载。

您必须使用您提到的第二个选项:

编辑:您可以Add在 Point 类本身中添加该方法

public Point Add(Point other){
    return new Point(this.x + other.x, this.y + other.y);
}
Run Code Online (Sandbox Code Playgroud)

  • 在可变类中,更改现有实例是正常的,尽管将“Point”设置为不可变值会更好。(另外,“add”中的“a”应该是小写的。) (3认同)