Kotlin for android 学习笔记 5 继承

Kotlin中的类默认是final类型的,想要被继承,得用“open”关键字修饰。

open class Shape {}

class Rectangle : Shape {}

子类的所有构造构造方法必须直接或间接调用一个父类的构造方法

open class Shape {
    constructor(name: String) {
        print(name)
    }
}

class Rectangle : Shape {
    constructor(name: String) : super(name) {}

    constructor(name: String, age: Int) : this(name) {}
}

子类的所有构造构造方法必须直接或间接调用一个父类的构造方法

open class Shape {
    constructor(name: String) {
        print(name)
    }
}

class Rectangle : Shape {
    constructor(name: String) : super(name) {}

    constructor(name: String, age: Int) : this(name) {}
}

成员方法重写

继承过程中,只有open修饰的方法才能被重写,重写时要用override修饰。
open特性也能被继承,想要断了open特性,只需用final修饰即可。

open class Shape {
    open fun method() {}
}

open class Rectangle : Shape() {
    override fun method() {}
}

class Square : Rectangle() {
    final override fun method() {}
}

成员变量重写

与方法重写相同,只有open修饰的变量才能被重写,open同样可以继承,也可以用final中断。
重写过程中,变量可由val类型变为var类型,反之则不行。

open class Shape {
    open val name: String = "Shape"
}

open class Rectangle : Shape() {
    override var name: String = "Rectangle"
}

class Square : Rectangle() {
    final override var name = "Square"
}

调用父类方法和变量

  • 可通过“super”关键字调用父类的方法和成员变量
open class Shape {
    open val name: String = "Shape"
    open fun draw() {}
}

open class Rectangle : Shape() {
    override var name: String = super.name
    override fun draw() {
        super.draw()
    }
}

  • 内部类调用外部类父类的方法 使用“super@Outer”方式:
open class Sup {
    open fun method() { println("Sup.method") }
}

class Sub:Sup(){
    inner class Inner{
        fun test(){
            super@Sub.method()
        }
    }
}

  • 当继承的类和接口当中出现相同的方法(方法名和参数都相同),通过类似泛型的方法明确调用哪个方法
interface Action {
    fun eat() {
        println("Action")
    }
}

open class Animal {
    open fun eat() {
        println("Animal")
    }
}

class Human() : Animal(), Action {
    override fun eat() {
        super<Action>.eat()
        super<Animal>.eat()
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值