接口和抽象类 3个月前

编程语言
990
接口和抽象类

抽象类

abstract class Person(open val age: Int){
    abstract fun work()
}

class MaNong(age: Int): Person(age){

    override val age: Int
        get() = 0

    override fun work() {
        println("我是码农,我在写代码")
    }
}

class Doctor(age: Int): Person(age){
    override fun work() {
        println("我是医生,我在给病人看病")
    }
}

fun main(args: Array<String>) {
    val person: Person = MaNong(23)
    person.work()
    println(person.age)

    val person2 : Person = Doctor(24)
    person2.work()
    println(person2.age)
}

接口代理

class Manager: Driver, Writer {
    override fun write() {

    }

    override fun drive() {

    }
}

class SeniorManager(val driver: Driver, val writer: Writer): Driver by driver, Writer by writer

class CarDriver: Driver {
    override fun drive() {
        println("开车呢")
    }
}

class PPTWriter: Writer {
    override fun write() {
        println("做PPT呢")
    }

}

interface Driver{
    fun drive()
}

interface Writer{
    fun write()
}

fun main(args: Array<String>) {
    val driver = CarDriver()
    val writer = PPTWriter()
    val seniorManager = SeniorManager(driver, writer)
    seniorManager.drive()
    seniorManager.write()
}
image
EchoEcho官方
无论前方如何,请不要后悔与我相遇。
1377
发布数
439
关注者
2222966
累计阅读

热门教程文档

HTML
32小节
PHP
52小节
Golang
23小节
Lua
21小节
Objective-C
29小节