设计一个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,更友好的输出点的信息。
package t2
/*
6.apply 单例模式
7.伴生类 伴生对象
8.多个类
9.继承
class 子类 extends 父类
11.子类对父类的方法的 重写
在子类中,通过override覆盖(重写)父类的同名方法
12.super. 在子类中访问父类
13.面向对象编程的三大特征:封装、继承、多态
14.构造器的调用顺序:先调用父类,再调用子类的
15.当父类,子类都存在带参数的构造器的时候,如何进行参数传递?
*/
object test13 {
class Point(var x: Double, var y: Double) {
def whereAmI(): String = {}
def getDist(): Double = {
Math.sqrt(this.x * this.x + this.y * this.y)
}
def formPoint(other: Point): Double = {
Math.sqrt((this.x - other.x) * (this.x - other.x) + (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.formPoint(p2))
}
}
def wherAmI():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){
"y轴上"
}else if (y==0 && x!=0){
"x轴上"
}else if (x==0 && y==0){
"原点"
}else{
"未知"
}
}