Person1类
package kmust.hjr.learningScala12
/**
* Created by Administrator on 2015/7/14.
*/
class Person1(val name:String,var age:Int){
println("The primary constructor of Person1 !")
val school="KMUST"
def sleep="8 hours"
override def toString="I am a Student of KMUST !"
}
说明:override 重写字段或者类的属性或方法的关键字
所有的对象都有toString()方法,所以可以直接覆写toString()方法;(例如所有的java类都继承Object)
Worker类-继承Person1类
注意:子类在表达继承父类的时候,必须把父类的主构造器的所有参数都填充满
在表达继承的时候就填充父类主构造器参数,如下所示:
class Worker(name:String,age:Int,val salary:Long)extends Person1(name,age)
class Worker(name:String,age:Int,val salary:Long)extends Person1(name,age){
println("This is the subClass of Person1,Primary constructor of Worker !")
override val school="CQUT"
override def toString="I am a Worker !"+super.sleep
}
说明:在子类中调用父类的方法采用super关键字
父类中的sleep方法,在子类中调用,则采用super.sleep
main函数
object OverrideOperation {
def main(args:Array[String]): Unit ={
val w=new Worker("HJR",25,500000)
println("School:"+w.school)
println("Salary:"+w.salary)
println(w.toString)
}
}