11

25 阅读1分钟
package level02

object class05 {
  class Point(var x: Double, var y: Double) {
    def whereAmI(): String = {  s"I am at Point($x, $y)" }

    def getDist(): Double = {
      Math.sqrt(x * x + y * y)
    }

    def fromPoint(other: Point): Double = {
      val dx = other.x - x
      val dy = other.y - y
      Math.sqrt(dx * dx + dy * dy)
    }

    override def toString: String = s"Point($x, $y)"

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

  // 作业
  class LabelPoint(x: Double, y: Double) extends Point(x, y){
  }

  def main(args: Array[String]): Unit = {
    // 测试
    val p1 = new Point(0.1, 1.0)
    val p2 = new Point(0.1, 1.0)
    println(p1.whereAmI())
    println(p1.getDist())
    println(p1.fromPoint(p2))
    println(p1 == p2)
  }
}