栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

(十五)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)
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/881773.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号