(十五)Kotlin简单易学 基础语法-类继承与重载open关键字
继承
类默认都是封闭的,要让某个类开发继承,必须使用open关键字修饰它。
open class Product(var name:String) {
fun description()= "Product: $name"
open fun load() = "Noting.."
}
class LuxuryProduct :Product("Luxury"){
override fun load() = "Luxury loading"
}
fun main() {
val p:Product = LuxuryProduct()
print(p.load())
}
类型检测
Kotlin的is运算符是个不错的工具,可以用来检查某个对象的类型
open class Product(var name:String) {
fun description()= "Product: $name"
open fun load() = "Noting.."
}
class LuxuryProduct :Product("Luxury"){
override fun load() = "Luxury loading"
}
fun main() {
val p:Product = LuxuryProduct()
print(p is Product)
print(p is LuxuryProduct)
print(p is File)
}
类型转换
open class Product(var name: String) {
fun description() = "Product: $name"
open fun load() = "Noting.."
}
class LuxuryProduct : Product("Luxury") {
override fun load() = "Luxury loading"
fun special() = "LuxuryProduct special function"
}
fun main() {
val p: Product = LuxuryProduct()
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 fun load() = "Luxury loading"
fun special() = "LuxuryProduct special function"
}
fun main() {
val p: Product = LuxuryProduct()
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 fun load() = "Luxury loading"
fun special() = "LuxuryProduct special function"
}
fun main() {
val p: Product = LuxuryProduct()
print(p is Any)
}
|