练习例题:
例题代码如下:
object day63 {
class Point(var x:Double, var y:Double) {
def whereAmI():String = {
if(x >0 && y >0){
"第1象限"
} else if(x>0 && y < 0){
"第4象限"
} else if(x<0 && y < 0){
"第3象限"
}else if(x<0 && y > 0){
"第2象限"
} else if(x ==0 && y != 0){
"y轴上"
} else if(y ==0 && x != 0){
"x轴上"
} else if(x ==0 && x == 0){
"原点"
} else {
"未知"
}
}
def getDist():Double = {
Math.sqrt( this.x * this.x + this.y * this.y )
}
def fromPoint(other:Point):Double = {
Math.sqrt( (this.x-other.x) * (this.x-other.x) + (this.y-other.y) * (this.y-other.y ) )
}
override def equals(obj: Any): Boolean = {
val other = obj.asInstanceOf[Point]
this.x == other.x && this.y == other.y
}
override def toString: String = {
s"Point(${x}, ${y})"
}
}
def main(args: Array[String]): Unit = {
val p1 = new Point(1,1)
val p2 = new Point(1,1)
println(p1 == p2)
println(p1.whereAmI())
println(p1.getDist())
println(p1.fromPoint(p2))
}
}
1. Point 类
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)"
}
}
2. LabelPoint 子类
class LabelPoint(label: String, x: Double, y: Double) extends Point(x, y) {
override def toString: String = {
s"LabelPoint($label, $x, $y)"
}
}
代码说明
- Point 类:通过构造器接收
x和y坐标,实现了 5 个方法,分别用于判断象限、计算到原点距离、计算与其他点的距离、判断点是否相同以及友好输出点信息。 - LabelPoint 类:继承自
Point类,构造器接收标签和坐标,重写toString方法以包含标签信息。