(十五)Kotlin简单易学 基础语法-类继承与重载open关键字

(十五)Kotlin简单易学 基础语法-类继承与重载open关键字,第1张

(十五)Kotlin简单易学 基础语法-类继承与重载open关键字

继承

类默认都是封闭的,要让某个类开发继承,必须使用open关键字修饰它。

open class Product(var name:String) {
    fun description()= "Product: $name" 
    //open关键字修饰它,子类才可以重写
    open fun load() = "Noting.."
}

// //open关键字修饰它,子类才可以继承
class LuxuryProduct :Product("Luxury"){
    //覆盖override
   override fun load() = "Luxury loading"
}

fun main() {
    val p:Product = LuxuryProduct()
    //Luxury loading
    print(p.load())
}

类型检测

Kotlin的is运算符是个不错的工具,可以用来检查某个对象的类型

open class Product(var name:String) {
    fun description()= "Product: $name"

    open fun load() = "Noting.."
}


class LuxuryProduct :Product("Luxury"){
    //覆盖override
   override fun load() = "Luxury loading"
}

fun main() {
    val p:Product = LuxuryProduct()
    //输出true
    print(p is Product)
    //输出true
    print(p is LuxuryProduct)
    //输出false
    print(p is File)

}

类型转换


open class Product(var name: String) {
    fun description() = "Product: $name"

    open fun load() = "Noting.."
}


class LuxuryProduct : Product("Luxury") {
    //覆盖override
    override fun load() = "Luxury loading"

    fun special() = "LuxuryProduct special function"
}

fun main() {
    val p: Product = LuxuryProduct()
    //输出LuxuryProduct special function
    //类型转换
    if (p is LuxuryProduct) {
        print(p.special())
    }
}

智能类型转换

Kotlin编译器很聪明,只要能确定any is 父类条件检查属实,它就会将any当作字类对象对待,因此 编译器允许你不经类型转换直接使用。


open class Product(var name: String) {
    fun description() = "Product: $name"

    open fun load() = "Noting.."
}


class LuxuryProduct : Product("Luxury") {
    //覆盖override
    override fun load() = "Luxury loading"

    fun special() = "LuxuryProduct special function"
}

fun main() {
    val p: Product = LuxuryProduct()
    //输出LuxuryProduct special function
    print((p as LuxuryProduct).special())
}

Kotlin层次

无须在代码里显示指定,每一个类都会继承一个共同的叫做Any的超类。


open class Product(var name: String) {
    fun description() = "Product: $name"

    open fun load() = "Noting.."
}


class LuxuryProduct : Product("Luxury") {
    //覆盖override
    override fun load() = "Luxury loading"

    fun special() = "LuxuryProduct special function"
}

fun main() {
    val p: Product = LuxuryProduct()
    //输出true
    print(p is Any)
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/918741.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存