(一)面向对象:
它是一种编程思想,它是基于面向对象的,强调的是以对象为基础完成各种操作。
1. 面向对象的三大特征是
(1) 封装
(2) 继承
(3) 多态
(二)创建类和对象:
package level02
object class01 {
//class 类
//Student 构造函数,用来创建对象,new 的时候,就会自动调用一次
// 构造函数:
// (1)主构造函数
// (2)辅助构造函数
// 特点:名字就叫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()
}
}