Java 类定义:平面直角坐标系中的点类 Point

本文将讲解如何使用 Java 语言定义一个 Point 类,用于描述平面直角坐标系中的点,并实现获取、设置坐标值、计算两点距离、平移点等操作。

一、类定义

public class Point {
    // 定义私有属性
    private double x;
    private double y;

    // 构造方法
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    // 获取横坐标
    public double getX() {
        return x;
    }

    // 获取纵坐标
    public double getY() {
        return y;
    }

    // 设置横坐标
    public void setX(double x) {
        this.x = x;
    }

    // 设置纵坐标
    public void setY(double y) {
        this.y = y;
    }

    // 计算两点之间的距离
    public double distance(Point other) {
        double dx = this.x - other.x;
        double dy = this.y - other.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    // 平移点
    public void translate(double dx, double dy) {
        this.x += dx;
        this.y += dy;
    }

    // 打印点的坐标信息
    public void printCoordinates() {
        System.out.println('Point coordinates: (' + x + ', ' + y + ')');
    }
}

二、代码解析

  • 属性定义:
    • private double x;private double y; 定义了点的横坐标和纵坐标,它们是私有属性,只能在类内部访问。
  • 构造方法:
    • public Point(double x, double y) 是构造方法,用于创建 Point 对象并初始化其横坐标和纵坐标。
  • 获取方法:
    • public double getX()public double getY() 是获取横坐标和纵坐标的公有方法,允许外部代码访问对象的属性。
  • 设置方法:
    • public void setX(double x)public void setY(double y) 是设置横坐标和纵坐标的公有方法,允许外部代码修改对象的属性。
  • 距离计算方法:
    • public double distance(Point other) 计算当前点与另一个点之间的距离,返回距离值。
  • 平移方法:
    • public void translate(double dx, double dy) 将当前点平移指定的距离,修改横坐标和纵坐标。
  • 打印坐标方法:
    • public void printCoordinates() 将当前点的坐标信息打印到控制台。

三、代码示例

public class Main {
    public static void main(String[] args) {
        // 创建两个点对象
        Point point1 = new Point(1.0, 2.0);
        Point point2 = new Point(4.0, 6.0);

        // 打印点 1 的坐标信息
        point1.printCoordinates();

        // 计算两点之间的距离
        double distance = point1.distance(point2);
        System.out.println('Distance between point1 and point2: ' + distance);

        // 平移点 1
        point1.translate(2.0, 3.0);
        System.out.println('Point 1 after translation: ' + point1.getX() + ', ' + point1.getY());
    }
}

四、总结

通过以上代码,我们定义了一个简单的 Point 类,实现了平面直角坐标系中点的坐标操作。通过封装属性和方法,保证了数据的完整性和代码的可维护性。在实际开发中,可以根据需要扩展 Point 类,添加更多操作方法,使其更加完善。

Java 类定义:平面直角坐标系中的点类 Point

原文地址: http://www.cveoy.top/t/topic/fah9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录