(十五)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"){//覆盖overrideoverride fun load() = "Luxury loading"
}fun main() {val p:Product = LuxuryProduct()//Luxury loadingprint(p.load())
}
类型检测
Kotlin的is运算符是个不错的工具,可以用来检查某个对象的类型
open class Product(var name:String) {fun description()= "Product: $name"open fun load() = "Noting.."
}class LuxuryProduct :Product("Luxury"){//覆盖overrideoverride fun load() = "Luxury loading"
}fun main() {val p:Product = LuxuryProduct()//输出trueprint(p is Product)//输出trueprint(p is LuxuryProduct)//输出falseprint(p is File)}
类型转换
open class Product(var name: String) {fun description() = "Product: $name"open fun load() = "Noting.."
}class LuxuryProduct : Product("Luxury") {//覆盖overrideoverride 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") {//覆盖overrideoverride fun load() = "Luxury loading"fun special() = "LuxuryProduct special function"
}fun main() {val p: Product = LuxuryProduct()//输出LuxuryProduct special functionprint((p as LuxuryProduct).special())
}
Kotlin层次
无须在代码里显示指定,每一个类都会继承一个共同的叫做Any的超类。
open class Product(var name: String) {fun description() = "Product: $name"open fun load() = "Noting.."
}class LuxuryProduct : Product("Luxury") {//覆盖overrideoverride fun load() = "Luxury loading"fun special() = "LuxuryProduct special function"
}fun main() {val p: Product = LuxuryProduct()//输出trueprint(p is Any)
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
