/**
* 构造器
**/
object ConstructorApp {
def main(args: Array[String]): Unit = {
// val person = new Person("若泽", 30)
// println(s"name is: ${person.name}, age is: ${person.age}")
// val p2 = new Person("PK哥", 31, "M") // 调用的附属构造器
// println(s"name is: ${p2.name}, age is: ${p2.age}, gender is: ${p2.gender}")
/**
* 继承:new 子类时
* 先调用父类构造器,再调用子类构造器
*/
val student = new Student("若泽", 30, "cs")
// println(s"name is: ${student.name}, " +
// s"age is: ${student.age}, major is: ${student.major}, school is ${student.school}")
println(student.toString()) // full@hash
}
}
/**
* class 类名(....) 在Scala中叫做主构造器
*
* 附属构造器
*/
class Person(val name:String, val age:Int) { // 默认也把括号中定义的东西转成属性
println("Person Constructor enter...")
val school = "pku"
var gender:String = _
/**
* 附属构造器
* 1) def this定义的叫做附属构造器
* 2) 一个附属构造器中第一行必须要调用主构造器或者其他附属构造器
*/
def this(name:String, age:Int, gender:String) {
this(name, age) // 调用主构造器
this.gender = gender
}
// 默认class里面是有一个toString
override def toString() = "父类的toString方法"
println("Person Constructor leave...")
}
/**
* 继承:父和子之间
*/
class Student(name:String, age:Int, val major:String) extends Person(name,age) {
println("Student Constructor enter...")
// 父子之间:属性的重写
override val school = "nudt"
// 父子之间:方法的重写
override def toString() = "子类的toString方法"
/**
* 重写来说,需要一个关键字override来修饰
*/
println("Student Constructor enter...")
}
/**
* public class Person {
* private final java.lang.String name;
* private final int age;
*
* public java.lang.String name();
* public int age();
*
* public Person(java.lang.String, int);
* }
*/
输出结果:
Person Constructor enter...
Person Constructor leave...
Student Constructor enter...
Student Constructor enter...
子类的toString方法