当前位置:   article > 正文

Kotlin对象继承— 方法的覆盖_kotlin model继承

kotlin model继承
package com.init.demo.model

/**
 * 对象继承— 方法的覆盖
 */
open class DemoPersonMethodOverride(name: String, age: Int, height: Int, likeFood: String, costByMonth: Int) {

    val name: String = name
    val age: Int = age
    val height: Int = height
    val likeFood: String = likeFood
    val costByMonth: Int = costByMonth
    /**
     *在方罚面前添加open,表明这个方法可以被覆盖
     * 如果方法面前不添加任何修饰符,那么kotlin会默认在前面添加final
     * 那么方法就是不可以被继承,不可以被覆盖
     */
   open fun  printInfomation() = println("(name='$name', age=$age, height=$height, likeFood='$likeFood', costByMonth=$costByMonth)")
}

class StudentMethodOverride(name: String, age: Int, height: Int, likeFood: String, costByMonth: Int,teacherNumbers :Int,schoolNmae :String):DemoPersonMethodOverride(name, age, height, likeFood, costByMonth){
    var teacherNumbers :Int = teacherNumbers
    var schoolNmae :String = schoolNmae

    override fun printInfomation() {
//        super.printInfomation()
        println("(name='$name', age=$age, height=$height, likeFood='$likeFood', costByMonth=$costByMonth), teacherNumbers=$teacherNumbers), schoolNmae=$schoolNmae)")

    }
}

class WorkerMethodOverride(name: String, age: Int, height: Int, likeFood: String, costByMonth: Int,sqlary :Int,nameOfWorkPlace :String):DemoPersonMethodOverride(name, age, height, likeFood, costByMonth){
    var sqlary :Int = sqlary
    var nameOfWorkPlace :String = nameOfWorkPlace

    /**
     * 在子类重写超类方法时,需要在方法前面加上override
     */
    override fun printInfomation() {
//        super.printInfomation()
        println("(name='$name', age=$age, height=$height, likeFood='$likeFood', costByMonth=$costByMonth), sqlary=$sqlary), nameOfWorkPlace=$nameOfWorkPlace)")
    }
}

fun main(args: Array<String>) {
    val student = StudentMethodOverride("小明",20,180,"beef",800,10,"CHONGING UNIVERSITY")
    student.printInfomation()
    val worker = WorkerMethodOverride("大明",40,170,"beefLike",1600,5000,"CHONGING UNIVERSITY")
    worker.printInfomation()
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/277383
推荐阅读
相关标签
  

闽ICP备14008679号