1 子类采用主构造函数
//Person.kt
package com.example.xhello
import android.app.Person
open class Person {
var name = ""
var age = 0
fun eat() {
println(name + "is eating. He is + " + age + "years old.")
}
}
//Student.kt
import android.app.Person
class Student(val sno: String, val grade: Int) : com.example.xhello.Person() {
}
//learnKotlin.kt
val student = Student("a123", 5)
println("student grade is" + student.grade)
println("student son is" + student.sno)
student.eat()
运行结果如图所示:
2 子类采用主构造函数
//Person.kt
package com.example.xhello
import android.app.Person
open class Person (val name: String, val age: Int){
}
//Student.kt
package com.example.xhello
import android.app.Person
class Student(val sno: String, val grade: Int, name:String, age: Int) :
com.example.xhello.Person(name, age) {
init {
println("Sno is " + sno)
println("grade is " + grade )
}
}
3 子类中既有主构造函数也有次构造函数
//Person.kt
package com.example.xhello
import android.app.Person
open class Person (val name: String, val age: Int){
}
//Student.kt
package com.example.xhello
import android.app.Person
class Student(val sno: String, val grade: Int, name:String, age: Int) :
com.example.xhello.Person(name, age) {
constructor(name: String, age: Int) : this("", 0, name, age){
}
constructor() : this("", 0){
}
}
4 子类中只含有此构造函数
//Person.kt
package com.example.xhello
import android.app.Person
open class Person (val name: String, val age: Int){
}
//Student.kt
package com.example.xhello
import android.app.Person
class Student : com.example.xhello.Person {
constructor(name: String, age: Int) : super(name, age){
}
}