qimo

17 阅读1分钟

image.png

class Point(var x: Double, var y: Double) {
  // 方法1:判断所在象限
  def whereAmI(): String = {
    if (x > 0 && y > 0) "第一象限"
    else if (x < 0 && y > 0) "第二象限"
    else if (x < 0 && y < 0) "第三象限"
    else if (x > 0 && y < 0) "第四象限"
    else if (x == 0 && y == 0) "原点"
    else if (x == 0) "y轴上"
    else "x轴上"
  }

  // 方法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 p: Point => p.x == this.x && p.y == this.y
      case _ => false
    }
  }

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


```scala
class LabelPoint(label: String, x: Double, y: Double) extends Point(x, y) {
  override def toString: String = {
    s"LabelPoint($label, $x, $y)"
  }
}