Scala中的类和对象

39 阅读1分钟

类是属性和行为的集合。class 类。

(1) 属性也叫成员变量:名词,用来描述事物的外在特征

(2) 行为也叫成员方法:动词,表示事物能做什么

创建类

Student 构建函数,用来创建对象,new 的时候,就会自动调用一次

构建函数:

  1. 主构造函数
  2. 辅助构造函数

辅助构造器的方法名固定为this,其参数不能使用var或val修饰,且必须在第一行代码中直接或间接调用主构造器。可以有多个辅助构造函数。

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

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

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

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

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

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

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

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