主要内容:
1.主构造函数的参数 2.this关键字链式风格 3.辅助构造函数
(一)主构造函数的参数
参数修饰符的三种情况:var 和 val的区别?
1. var 是可以修改的属性
2. val 是不可以修改的属性
3.而没有使用val或者var修饰的,不是属性,不可在外部访问,不可改写。
代码如下:
class Student(var name:String,var age :Int) {
println("构建函数被调用...")
def sayHi():Unit={
println(s"我是${name},我今年${age}")
}
def this ()={
this ("无名氏",0)
println("辅助构建函数1被调用...")
}
def this (name:String)={
this(name,0)
println("辅助构建函数2被调用...")
}
}
object base060 {
def main(args: Array[String]): Unit = {
// 创建一个学生对象
// val stu1= new Student("小花",18)
// 调用对象的方法
// stu1.sayHi()
// stu1.age=19
// 调用对象的方法
// stu1.sayHi()
// 这里设置参数,它会辅助构建函数
// val stu2 = new Student()
// stu2.sayHi()
// 这里设置了一个参数,它会调用辅助构建函数
val stu3 = new Student("小明")
stu3.sayHi()
}
}
结果如下:
(二)主构造函数的参数
this在类内部表示当前对象,我们可以利用这个特点实现对象方法的链式调用。
[ 问 ] 如何实现对象.方法1().方法2().方法3()...
[讲] 格式:对象.方法1().方法2().方法3()...
原理:在方法中返回this 代码如下:
class Student(var name:String,var age :Int) {
println("构建函数被调用...")
def sayHi():Unit={
println(s"我是${name},我今年${age}")
}
def this ()={
this ("无名氏",0)
println("辅助构建函数1被调用...")
}
def this (name:String)={
this(name,0)
println("辅助构建函数2被调用...")
}
}
object base060 {
def main(args: Array[String]): Unit = {
// 创建一个学生对象
// val stu1= new Student("小花",18)
// 调用对象的方法
// stu1.sayHi()
// stu1.age=19
// 调用对象的方法
// stu1.sayHi()
// 这里设置参数,它会辅助构建函数
// val stu2 = new Student()
// stu2.sayHi()
// 这里设置了一个参数,它会调用辅助构建函数
val stu3 = new Student("小明")
stu3.sayHi()
}
}
(二)this关键字链式风格
this在类内部表示当前对象,我们可以利用这个特点实现对象方法的链式调用。
[问] 如何实现对象.方法1().方法2().方法3()...
[讲] 格式:对象.方法1().方法2().方法3()...
原理:在方法中返回this
def sayHello():this.type= {
this
}
def eat():this.type= {
this
}
s = new Student()
s.sayHello().eat().say()
(三)辅助构造函数
格式
辅助构造器的方法名固定为this,其参数不能使用var或val修饰,且必须在第一行代码中直接或间接调用主构造器
class Student(var name:String,var age :Int) {
println("构建函数被调用...")
def sayHi():Unit={
println(s"我是${name},我今年${age}")
}
def this ()={
this ("无名氏",0)
println("辅助构建函数1被调用...")
}
def this (name:String)={
this(name,0)
println("辅助构建函数2被调用...")
}
}
object base060 {
def main(args: Array[String]): Unit = {
// 创建一个学生对象
// val stu1= new Student("小花",18)
// 调用对象的方法
// stu1.sayHi()
// stu1.age=19
// 调用对象的方法
// stu1.sayHi()
// 这里设置参数,它会辅助构建函数
// val stu2 = new Student()
// stu2.sayHi()
// 这里设置了一个参数,它会调用辅助构建函数
val stu3 = new Student("小明")
stu3.sayHi()
}
}