android kotlin 基础复习 继承 inherit

1、新建文件kt

2、代码:

复制代码
/**用户基类**/
open class Person1(name:String){
    /**次级构造函数**/
    constructor(name:String,age:Int):this(name){
        //初始化
        println("-------基类次级构造函数---------")
        println("name:${name},age:${age}")
    }
}

/**子类继承 Person 类**/
class Student1:Person1{

    /**次级构造函数**/
    constructor(name:String,age:Int,no:String,score:Int):super(name,age){
        println("-------继承类次级构造函数---------")
        println("学生名: ${name}")
        println("年龄: ${age}")
        println("学生号: ${no}")
        println("成绩: ${score}")
    }
}


/**用户基类**/
open class Person2{
    open fun study(){       // 允许子类重写
        println("我毕业了")
    }
}

/**子类继承 Person 类**/
class Student2 : Person2() {

    override fun study(){    // 重写方法
        println("我在读大学")
    }
}

open class A {
    open fun f () { print("A") }
    fun a() { println("a") }
}

interface B {
    fun f() { println("B") } //接口的成员变量默认是 open 的
    fun b() { println("b") }
}

class C() : A() , B{
    override fun f() {
        super<A>.f()//调用 A.f()
        super<B>.f()//调用 B.f()
        super.b()
    }
}

fun main(args: Array<String>) {
    var s =  Student1("Runoob", 18, "S12345", 89)
    println("--------- s2 -------")
    val s2 =  Student2()
    s2.study()
    println("--------- c -------")
    val c =  C()
    c.f()
}

3、输出:

4、Student1也可以这样写:

复制代码
/**子类继承 Person 类**/
class Student1(name: String, age: Int, no: String, score: Int) : Person1(name, age) {

    init {
        println("-------继承类次级构造函数---------")
        println("学生名: ${name}")
        println("年龄: ${age}")
        println("学生号: ${no}")
        println("成绩: ${score}")
    }
}

5、说明:

oop中,一般抽象出共同的特性形成一个类,比如person有一个name。

student继承了以后,也具有了这个属性name,然后还可以增加属于自己的属性,形成一个更加具

体的类。比如:只有学生才有学生号、成绩等。

相关推荐
爱学啊41 分钟前
3.Android Compose 基础系列:在 Kotlin 中创建和使用函数
kotlin·compose·android compose开发基础
行墨1 小时前
Jetpack Compose 深入浅出(二)——基础组件Text
android
低调小一3 小时前
LRU缓存科普与实现(Kotlin 与 Swift)
开发语言·缓存·kotlin
雨白3 小时前
深入理解协程的运作机制 —— 调度、挂起与性能
android·kotlin
沐怡旸3 小时前
【Android】Android系统体系结构
android
namehu3 小时前
React Native 应用性能分析与优化不完全指南
android·react native·ios
xqlily4 小时前
Kotlin:现代编程语言的革新者
android·开发语言·kotlin
HelloBan4 小时前
如何正确去掉SeekBar的Thumb和按压效果
android
木易 士心4 小时前
Android EventBus 源码解析:设计模式、原理与实现
android
ClassOps4 小时前
源码阅读 LeakCanary
android