习题:设计一个point类

27 阅读2分钟

设计一个point类,其x和y坐标都是通过构造器提供的

它有几个方法:

1.方法1:计算自己在哪个象限。 whereAmI():String

2.方法2:计算自己与原点距离。 getDist():Double

3.方法3:计算与另一个点的距离。fromPoint(other:Point):Double

4.方法4:重写equals 判断是否是同一个点(x和y都相等就是同一个 点)

5.方法5:重写toString,更友好的输出点的信息

在设计一个子类LabelPoint它来继承Point类,其中构造器接收一个标签值和x,y坐标

object class13 {
  // Point类(deepseek)
  class Point(val x: Double, val y: Double) {

    // 方法1:计算自己在哪个象限
    def whereAmI(): String = {
      (x, y) match {
        case (0, 0) => "原点"
        case (0, _) => "Y轴"
        case (_, 0) => "X轴"
        case (x, y) if x > 0 && y > 0 => "第一象限"
        case (x, y) if x < 0 && y > 0 => "第二象限"
        case (x, y) if x < 0 && y < 0 => "第三象限"
        case (x, y) if x > 0 && y < 0 => "第四象限"
      }
    }

    // 方法2:计算自己与原点距离
    def getDist(): Double = {
      math.sqrt(x * x + y * y)
    }

    // 方法3:计算与另一个点的距离
    def fromPoint(other: Point): Double = {
      math.sqrt(math.pow(x - other.x, 2) + math.pow(y - other.y, 2))
    }

    // 方法4:重写equals
    override def equals(obj: Any): Boolean = obj match {
      case that: Point => this.x == that.x && this.y == that.y
      case _ => false
    }

    // 方法5:重写toString
    override def toString: String = {
      s"Point(x=$x, y=$y)"
    }

    // 重写hashCode(通常与equals一起重写)
    override def hashCode(): Int = {
      (x, y).##
    }
  }

  // LabelPoint子类
  class LabelPoint(val label: String, x: Double, y: Double) extends Point(x, y) {

    // 重写toString方法
    override def toString: String = {
      s"LabelPoint(label='$label', x=$x, y=$y)"
    }

    // 可以添加标签相关的方法
    def getLabel(): String = label
  }

  // 伴生对象,提供工厂方法
  object Point {
    def apply(x: Double, y: Double): Point = new Point(x, y)
  }

  object LabelPoint {
    def apply(label: String, x: Double, y: Double): LabelPoint = new LabelPoint(label, x, y)
  }

  // 测试示例
  object PointTest extends App {
    // 创建Point实例
    val p1 = new Point(3, 4)
    val p2 = new Point(-2, 5)
    val p3 = new Point(3, 4)

    // 测试方法
    println(p1.whereAmI())  // 第一象限
    println(p2.whereAmI())  // 第二象限
    println(p1.getDist())   // 5.0
    println(p1.fromPoint(p2)) // 计算两点距离

    // 测试equals
    println(p1 == p3) // true
    println(p1 == p2) // false

    // 测试toString
    println(p1) // Point(x=3.0, y=4.0)

    // 测试LabelPoint
    val lp = new LabelPoint("中心点", 0, 0)
    println(lp.whereAmI()) // 原点
    println(lp) // LabelPoint(label='中心点', x=0.0, y=0.0)
    println(lp.getLabel()) // 中心点

    // 使用伴生对象创建实例
    val p4 = Point(1, 2)
    val lp2 = LabelPoint("测试点", 5, 6)
    println(p4)
    println(lp2)
  }
}