接口和抽象类

抽象类

  1. abstract class Person(open val age: Int){
  2. abstract fun work()
  3. }
  4. class MaNong(age: Int): Person(age){
  5. override val age: Int
  6. get() = 0
  7. override fun work() {
  8. println("我是码农,我在写代码")
  9. }
  10. }
  11. class Doctor(age: Int): Person(age){
  12. override fun work() {
  13. println("我是医生,我在给病人看病")
  14. }
  15. }
  16. fun main(args: Array<String>) {
  17. val person: Person = MaNong(23)
  18. person.work()
  19. println(person.age)
  20. val person2 : Person = Doctor(24)
  21. person2.work()
  22. println(person2.age)
  23. }

接口代理

  1. class Manager: Driver, Writer {
  2. override fun write() {
  3. }
  4. override fun drive() {
  5. }
  6. }
  7. class SeniorManager(val driver: Driver, val writer: Writer): Driver by driver, Writer by writer
  8. class CarDriver: Driver {
  9. override fun drive() {
  10. println("开车呢")
  11. }
  12. }
  13. class PPTWriter: Writer {
  14. override fun write() {
  15. println("做PPT呢")
  16. }
  17. }
  18. interface Driver{
  19. fun drive()
  20. }
  21. interface Writer{
  22. fun write()
  23. }
  24. fun main(args: Array<String>) {
  25. val driver = CarDriver()
  26. val writer = PPTWriter()
  27. val seniorManager = SeniorManager(driver, writer)
  28. seniorManager.drive()
  29. seniorManager.write()
  30. }