// 父类: name, age
class Animal(val name:String, var age: Int) {
println(s"父类构造器 ......${name} ${age}")
def eat():Unit = {
println(s"${name} ${age} eating.....")
}
}
// 子类: name,age, color
class Dog(name:String, age:Int, var color:String) extends Animal(name,age) {
println(s"子类构造器 .....${name} ${age} ${color}")
}
def main(args: Array[String]):Unit = {
val dog1 = new Dog("旺财", 1, "黑色")
dog1.eat()
作业
class Point(var x: Double, var y: Double) {
// 方法1:判断所在象限
def whereAmI(): String = {
(x, y) match {
case (0.0, 0.0) => "原点"
case (0.0, _) => "y轴上"
case (_, 0.0) => "x轴上"
case (x, y) if x > 0 && y > 0 => "第一象限"
case (x, y) if x < 0 && y > 0 => "第二象限"
case (x, y) if x < 0 && y < 0 => "第三象限"
case (x, y) if x > 0 && y < 0 => "第四象限"
}
}
// 方法2:计算到原点的距离
def getDist(): Double = {
math.sqrt(x * x + y * y)
}
// 方法3:计算与另一个点的距离
def fromPoint(other: Point): Double = {
val dx = x - other.x
val dy = y - other.y
math.sqrt(dx * dx + dy * dy)
}
// 方法4:重写equals判断是否为同一个点
override def equals(other: Any): Boolean = {
other match {
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
}
// 方法5:重写toString输出友好信息
override def toString: String = s"Point(x=$x, y=$y)"
子类
class LabelPoint(val label: String, x: Double, y: Double) extends Point(x, y) {
override def toString: String = s"LabelPoint(label='$label', x=$x, y=$y)"
}