You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中Point类的‘this Point’指代问题及相关概念咨询

Java中this与Point对象的指代问题解答

一、this Point的指代规则

  • this永远指向调用当前方法的那个Point对象实例,和变量名(比如first、second)无关:
    • 执行first.distance()时,this就是first对象;
    • 执行second.distance()时,this就变成second对象;
    • 执行point.distance()时,this就是那个无参构造创建的point对象。

二、this与Point(x,y)的区别

  • Point(x,y)是配合new关键字创建新对象的语法,比如new Point(3,1)会在内存中生成一个x=3、y=1的Point实例,再用变量(如second)引用它;
  • this是对当前方法所属已存在对象的引用,它不创建新对象,只是指向调用方法的那个实例。

三、补全后的Point类完整实现

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

    public Point() {
    }

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

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    // 计算到(0,0)的距离
    public double distance() {
        return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
    }

    // 计算到指定(x,y)点的距离
    public double distance(int x, int y) {
        return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2));
    }

    // 计算到另一个Point对象的距离
    public double distance(Point other) {
        return Math.sqrt(Math.pow(other.getX() - this.x, 2) + Math.pow(other.getY() - this.y, 2));
    }
}

方法说明

  • distance():this.x/this.y是当前调用对象的坐标,直接套用公式计算到原点(0,0)的距离;
  • distance(int x, int y):参数x/y是目标点坐标,this.x/this.y是当前对象坐标,代入公式计算两点距离;
  • distance(Point other):other是传入的目标Point对象,通过other.getX()/other.getY()获取目标坐标,和当前对象(this)的坐标计算距离。

内容的提问来源于stack exchange,提问作者Bryan Karlan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:07:09