class 类

37 阅读1分钟
object class01 {
  // class 类
  class Student(var name:String) {
    def sayHello(): Unit = {
      println(s"我是${name}")
    }
  }

  def main(args: Array[String]): Unit = {
    // 实例化类的对象 stu
    val stu = new Student("小花")
    // 调用对象的方法
    stu.sayHello()
  }
}
```
```

![image.png](https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/a5813ea05b7b4c6498cd480f070a65ac~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg6Zeq55S15bCP5a2QNzc=:q75.awebp?rk3s=f64ab15b&x-expires=1772608411&x-signature=HWzhyftIV4LlHRJCpDUbS4fcgTI%3D)


object class01 { // class 类

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

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

// 辅助构造函数
def this(name: String) {
  this(name, 15)
}

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()

} }

image.png

object class01 {
  // 特点:名字就叫this。它的代码的第一行必须是调用主构造器。可以有多个。
  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()
  }
}
```


```



image.png