ITPub博客

首页 > 应用开发 > Java > Scala的继承

Scala的继承

原创 Java 作者:541732025 时间:2015-11-16 19:55:38 0 删除 编辑

点击(此处)折叠或打开

  1. class Person1(val name : String, var age : Int){
  2.   println("The primary constructor of Person")
  3.   val school = "BJU"
  4.   def sleep = "8 hours"
  5.   override def toString = "I am a Person1!"
  6. }
跟在java中一样,任何class都是默认继承自object,这里override了toString方法

点击(此处)折叠或打开

  1. class Worker(name : String, age : Int, val salary : Long) extends Person1(name, age){ //创建Worker实例时,也会使用name、age填充父类实例。子类也必须将父类的主构造器的参数填满
  2.   println("This is the subClass of Person, Primary constructor of Worker")
  3.   override val school = "Spark" //覆盖父类的属性
  4.   override def toString = "I am a Worker!" + super.sleep //super调用父类的方法
  5. }

点击(此处)折叠或打开

  1. object OverrideOperations{
  2.   def main(args: Array[String]) {
  3.     val w = new Worker("Spark", 5, 100000)
  4.     println("School :" + w.school)
  5.     println("Salary :" + w.salary)
  6.     println(w.toString())
  7.   }
  8. }

结果:
The primary constructor of Person //先构造父类(跟java一样
This is the subClass of Person, Primary constructor of Worker //构建子类
School :Spark // 属性被覆盖
Salary :100000 //子类属性
I am a Worker!8 hours //子类覆盖

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1839810/,如需转载,请注明出处,否则将追究法律责任。

上一篇: Scala的apply
请登录后发表评论 登录
全部评论

注册时间:2013-05-23

  • 博文量
    127
  • 访问量
    479303