package com.init.demo.model /** * 对象继承—次构造函数的初始化 */ open class DemoPersonConstruction1{ var name: String = "" var age: Int = 0 var height: Int = 0 var likeFood: String = "" var costByMonth: Int = 0 constructor(name: String, age: Int, height: Int, likeFood: String, costByMonth: Int){ this.name = name this.age = age this.height = height this.likeFood = likeFood this.costByMonth = costByMonth } fun printInfomation() = println("(name='$name', age=$age, height=$height, likeFood='$likeFood', costByMonth=$costByMonth)") } /** *每个次构造函数不需使用super关键字对超类的属性进行初始化 * 具体写法:constructor 子类(次构造函数参数) :super(父类次构造函数参数){} */ class DemoStudentConstruction1 : DemoPersonConstruction1{ var teacherNumbers :Int = 0 var schoolNmae :String = "" constructor(name: String, age: Int, height: Int, likeFood: String, costByMonth: Int,teacherNumbers :Int,schoolNmae :String) : super(name, age, height, likeFood, costByMonth){ this.teacherNumbers = teacherNumbers this.schoolNmae = schoolNmae } } class DemoWorkerConstruction1 : DemoPersonConstruction1{ var sqlary :Int = 0 var nameOfWorkPlace :String = "" constructor(name: String, age: Int, height: Int, likeFood: String, costByMonth: Int,sqlary :Int,nameOfWorkPlace :String) : super(name, age, height, likeFood, costByMonth){ this.sqlary = sqlary this.nameOfWorkPlace = nameOfWorkPlace } } fun main(args: Array<String>) { val student = DemoStudentConstruction1("小明",20,180,"beef",800,10,"CHONGING UNIVERSITY") student.printInfomation() val worker = DemoWorkerConstruction1("大明",40,170,"beefLike",1600,5000,"CHONGING UNIVERSITY") worker.printInfomation() }
Kotlin对象继承—次构造函数的初始化
最新推荐文章于 2024-03-11 09:54:07 发布