zoukankan      html  css  js  c++  java
  • [Kotlin] Open Classes and Inheritance

     open class Person (open val name: String = "", open var age: Int) {
         init {}
         
         open fun greeting(pn: String) {
             println("$name says hello to $pn")
         }
     }
     
     class Student(override val name: String, override var age: Int = 18, val studentID: Long): Person(name, age) {
    
         override fun greeting(pn: String) {
             println("$name, $studentID says hello to $pn")
         }
     }
    
    fun main() {
        val p = Student(age=23, name="Jack", studentID=1234586L)
        p.greeting("Wan") // Jack, 1234586 says hello to Wan
    }

    Kotlin is very strict for inheritance, for the parent class, we have to add open keyword to the class and its methods and properties we want to extend.

    For the child class, we have to add override keywrod for the functions and properties we want to override.

  • 相关阅读:
    kindeditor的使用
    阅读笔记(三)
    阅读笔记(二)
    架构漫谈
    阅读笔记(一)
    hdfs
    暑假周总结八
    暑假周总结七
    暑假周总结六
    暑假周总结五
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13799227.html
Copyright © 2011-2022 走看看