Android Kotlin继承
16lz
2021-01-23
1 子类采用主构造函数
//Person.ktpackage com.example.xhelloimport android.app.Personopen class Person { var name = "" var age = 0 fun eat() { println(name + "is eating. He is + " + age + "years old.") }}
//Student.ktimport android.app.Personclass 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.ktpackage com.example.xhelloimport android.app.Personopen class Person (val name: String, val age: Int){}
//Student.ktpackage com.example.xhelloimport android.app.Personclass 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.ktpackage com.example.xhelloimport android.app.Personopen class Person (val name: String, val age: Int){}
//Student.ktpackage com.example.xhelloimport android.app.Personclass 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.ktpackage com.example.xhelloimport android.app.Personopen class Person (val name: String, val age: Int){}
//Student.ktpackage com.example.xhelloimport android.app.Personclass Student : com.example.xhello.Person { constructor(name: String, age: Int) : super(name, age){ }}
更多相关文章
- Android 中保存图片的代码
- android之将图片转化为圆形图片
- Android 使用decodeFile方法加载手机磁盘中的图片文件
- Android:使用SpannableString实现图片替换相应的文字
- Android 加载图片并存放在缓存中
- android 实现图片的裁剪
- Android ImageLoader组件加载图片
- Android 两个Activity切换时回调函数调用顺序
- 【Android网络编程】获取网络图片,具有缓存功能