Kotlin中的Class简单使⽤
Kotlin 中的Class
⽂章⽬录
特点
默认情况下,在Kotlin中,类是final类,不能⼦类化(被继承),只允许继承abstract class 或者被关键字open标记的class abstract class
abstract class Dwelling(private var residents:Int){
abstract val buildMaterial:String
abstract val capacity:Int
fun hasRoom():Boolean{
return residents < capacity
}
}
Subclass(⼦类)
class RoundHut(residents: Int):Dwelling(residents){
override val buildMaterial: String ="Stone"
override val capacity: Int =4
}
正确继承
open class RoundHut(residents: Int):Dwelling(residents){
override val buildMaterial: String ="Stone"
override val capacity: Int =4
}
class RoundTower(residents: Int):RoundHut(residents){
override val buildMaterial: String ="Stone"
override val capacity: Int =4
}
错误⽰范
This type is final, so it cannot be inherited from RoundHut
class RoundHut(residents: Int):Dwelling(residents){
override val buildMaterial: String ="Stone"
override val capacity: Int =4
}
class RoundTower(residents: Int):RoundHut(residents){
override val buildMaterial: String ="Stone"
override val capacity: Int =4
}
注意
定义抽象类时不需要使⽤open关键字, 因为当前表⽰abstract的,可以⼦类化的,修饰语open是多余的
Sample(例⼦)
fun main(){
val roundTower =RoundTower(4)
with(roundTower){
println("\nRound Tower\n ====")
println("Material:${buildMaterial}")
println("Material:${capacity}")
println("Has room?${hasRoom()}")
}
}
抽象类的使用Run and output(运⾏和输出)
Round Tower
====
Material:Stone
Material:4
Has room?false
关键字
with
定义:以给定的[receiver]作为其接收⽅,调⽤指定的函数[block]并返回其结果
with后跟()中的实例名,后跟包含要执⾏的操作的{}
with(roundTower){
println("\nRound Tower\n ====")
println("Material:${buildMaterial}")
println("Material:${capacity}")
println("Has room?${hasRoom()}")
}
这⾥[receiver] 是roundTower, {}⾥为函数块
多个参数的构造
class RoundTower(
residents: Int,
val floors: Int =2):RoundHut(residents){
override val buildMaterial: String ="Stone"
override val capacity: Int =4* floors
}
其中构造函数中声明 val floors: Int = 2 ,表⽰将floors赋值为2(默认值),当没有将floors的值传递给构造函数时,可以使⽤默认值创建对象实例
Sample
val roundTower =RoundTower(4)
with(roundTower){
println("\nRound Tower\n ====")
println("Material:${buildMaterial}")
println("Material:${capacity}")
println("Has room?${hasRoom()}")
}
Run and output(运⾏和输出)
Round Tower
====
Material:Stone
Material:8
Has room?true
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论