是否有可能在Java中重载运算符? [英] Is it possible to overload operators in Java?

查看:76
本文介绍了是否有可能在Java中重载运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

我怎样才能用Java做到这一点?或者我应该使用这样的方法:

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

提前致谢!

推荐答案

你不能用Java做到这一点。您必须在 Point 加上添加方法$ c> class。

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

用法

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中重载运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆