package Level02
class Point(val x: Double, val y: Double) {
def whereAmI(): String = {
if (x > 0 && y > 0) {
"第1象限"
} else if (x < 0 && y > 0) {
"第2象限"
} else if (x < 0 && y < 0) {
"第3象限"
} else if (x > 0 && y < 0) {
"第4象限"
} else {
"坐标轴上"
}
}
def getDist(): Double = {
Math.sqrt(x * x + y * y)
}
def fromPoint(other: Point): Double = {
val dx = other.x - this.x
val dy = other.y - this.y
Math.sqrt(dx * dx + dy * dy)
}
override def toString: String = s"Point(${x}, ${y})"
override def equals(obj: Any): Boolean = obj match {
case other: Point => this.x == other.x && this.y == other.y
case _ => false
}
override def hashCode(): Int = (x, y).hashCode()
}
class LabelPoint(x: Double, y: Double) extends Point(x, y) {
}
object class02 extends App {
val p1 = new Point(-0.1, 0.1)
val p2 = new Point(0.1, 0.1)
val p3 = new Point(-0.2, -0.2)
val p4 = new Point(0.3, -0.3)
val origin = new Point(0, 0)
println(s"$p1 位于:${p1.whereAmI()}")
println(s"$p2 位于:${p2.whereAmI()}")
println(s"$p1 到原点距离:${p1.getDist().formatted("%.3f")}")
println(s"$p1 到 $p2 的距离:${p1.fromPoint(p2).formatted("%.3f")}")
val labelPoint: Point = new LabelPoint(0.05, 0.05)
println(s"上转型对象 $labelPoint 位于:${labelPoint.whereAmI()}")
}
