学习scala中的class类

24 阅读1分钟

class 类

Student 构造函数(构造器),用来创建对象,new的时候,就会自动使用一次

构造函数:

(1)主构造函数

(2)辅助构造函数

特点:名字就叫this,它的代码的第一行必须是调用主构造器。可以有多个。

class Student(var name:String,var age:Int) {
    println("Student构造函数被调用......")

    // 辅助构造函数
    def this(name:String) {
        this(name,15)
        println("Student构造函数被调用......")

    }

    // 辅助构造函数
    def this(age:Int) {
        this("未知",age)
        println("Student构造函数被调用......")

    }

    def sayHello(): Unit = {
        println(s"我是${name},今年${age}")
    }

}

def main(args: Array[String]): Unit = {
    // 实例化类的对象
    // new 的时候,就会自动调用一次构造函数
    val stu = new Student("小花",18)

    // 调用对象的方法
    stu.sayHello()

    val stu1 = new Student("小明")
    stu1.sayHello()

    val stu2 = new Student(20)
    stu2.sayHello()

结果

Student构造函数被调用......
我是小花,今年18
Student构造函数被调用......
Student构造函数被调用......
我是小明,今年15
Student构造函数被调用......
Student构造函数被调用......
我是未知,今年20