scala学习笔记2(类,继承,抽象类)
class Person{ // _ 是占位符; var name : String = _ val age : Int = 27 // private[this] 定义的内容无法外部使用,起到保护作用; private[this] val gender = "male" } //类的构造函数,主构造器的使用; //1.主构造器直接跟在类名后面,主构造器中的参数会被编译成类的字段; //2.主构造器执行的时候会执行类中的所有不包含在方法体中的语句; //3.如果在主构造器函数中没有用 val 或者 var 去声明变量,那此时的变量是 private[this] 级别的,只能够被类内部访问 ; class Person1 (val name : String,val age : Int) { println("this is constructor") } //附属构造器: //1.附属构造器是用 this 来声明的; //2.附属构造器中必须调用主构造或者其他附属构造器; class Person2(var name : String , val age : Int) { println("this is constructor") var gender : String = _ def this(name : String , age : Int , gender : String) { this(name,age) this.gender = gender } val University = "BJU" } //scala中的继承 class Student (name : String , age : Int , val major : String) extends Person2(name , age){ println("student extends from person,major is : "+ major) // override 覆写父类的方法 override def toString = "override the method ..." // override 覆写字段 override val University = "tsinghua" } //scala中的抽象类,使用 abstract 关键字 abstract class people{ def speak val name : String var age : Int } class Worker extends people{ def speak{ println("I'm a worker") } val name = "lsw" var age = 21 } object OOPinScala{ def main(args : Array[String]){ val person = new Person person.name = "lucy" println(person.name + " : " + person.age) val person1 = new Person1("lucy",22) println(person1.name + " : " + person1.age) val person2 = new Person2("lsw",27,"male") println(person2.name+":"+person2.gender) val student = new Student("lsw" , 27 ,"computer") println(student.toString) println(student.University) val worker = new Worker() println(worker.name+" : "+ worker.age) } }
运行结果: