Scala--8--Scala构造器

    xiaoxiao2021-03-25  18

    package mxg.scala.test1 class Teacher {     var name: String = _     private var age = 20     private [this] val gender = "male"         def this(name:String) {//这就是构造器         this//用于调用主构造器(默认构造器) 一定会调用         this.name = name     }     def sayHello{         println(this.name +":" +this.age + ":" + this.gender)     } } class Student(val name:String , val age : Int){//类构造器  在构造器中写入了属性,类会自动添加构造器的属性     println ("This is the primary constructor!")         var gender : String = _         println(gender)         def this(name :String ,age : Int  , gender : String){         this(name,age)         this.gender = gender     } } class People private (val name  : String  ,  val  age : Int ){//私有化类构造器 只能调用重写的构造     println ("This is the primary constructor!")     var gender : String = _     println(gender)     def this(name :String ,age : Int  , gender : String){         this(name,age)         this.gender = gender     } }

    object OOPInScale{     def main(args: Array[String]){         val T = new Teacher         T.name = "Spark"         T.sayHello                 val s = new Student("Student" , 2)         println(s.age)                 val p = new People("People",10,"hello")         println(p.name + " " + p.age+ " " + p.gender)             }       }

    输出结果

    Spark:20:male This is the primary constructor! null 2 This is the primary constructor! null People 10 hello

    转载请注明原文地址: https://ju.6miu.com/read-200012.html

    最新回复(0)