Kotlin 基本语法5 继承,接口,枚举,密封

1.继承与重写的Open关键字

open class Product(
    val name:String
) {

    fun description() = "Product: $name"

   open fun load() = "Nothing .."


}


class LuxuryProduct:Product("Luxury"){//继承需要调用 父类的主构造函数

    override fun load(): String {
        return "LuxuryProduct loading ..."
    }

}

fun main() {
    val p:Product = LuxuryProduct()
    println(p.load())
}

2.类型检测

3.智能类型转化

import java.io.File

open class Product(
    val name:String
) {

    fun description() = "Product: $name"

   open fun load() = "Nothing .."


}


class LuxuryProduct:Product("Luxury"){//继承需要调用 父类的主构造函数

    override fun load(): String {
        return "LuxuryProduct loading ..."
    }
    fun  special():String = "Speical LuxuryProduct Function"

}

fun main() {
    val p:Product = LuxuryProduct()
    println(p.load())

    println(p is Product)
    println(p is LuxuryProduct)
    println(p is File)


    if (p is LuxuryProduct){
        p.special()
    }
}

4. Any 超类

跨平台支持得更好,他的Any类里的 toString hashcode equals 在不同平台有不同的实现,是为了更好的跨平台支持。

5. 对象

 5.1 object关键字 单例模式

object ApplicationConfig{
    var name :String = "singleName"
    init {
        println("ApplicationConfig loading ...")
    }
    fun doSomething(){
        println("doSomething")
    }


}

fun main() {
    //类名,实例名 就是一个单例对象
    ApplicationConfig.doSomething()
    println(ApplicationConfig)
    println(ApplicationConfig)
    println(ApplicationConfig)
    println(ApplicationConfig===ApplicationConfig)
}

5.2  对象表达式 相当于匿名内部类

open class Player{
    open fun load() = "loading nothing"
}

fun main() {
    val p = object : Player(){ //匿名内部类相当于
        override fun load(): String {
            return "anonymous nothing"
        }
    }
    println(p.load())
}

5.3 伴生对象 一个类只能有一个

import java.io.File

open class ConfigMap(val name:String){

    companion object{ //伴生对象  相当于静态内部类 创建的单例对象
        // 不管这个ConfigMap类实例化多少次,这个伴生对象就是单例,因为是不基于对象创建的,是类加载时创建的
        private const val PATH = "XXXX"

        var s:String ="asd"
        fun load() = File(PATH).readBytes()

    }

}

fun main() {
    ConfigMap.load()
}

import java.io.File

open class ConfigMap(val name:String){

    companion object{ //伴生对象  相当于静态内部类 创建的单例对象
        // 不管这个ConfigMap类实例化多少次,这个伴生对象就是单例,因为是不基于对象创建的,是类加载时创建的
        private const val PATH = "XXXX"

        var s:String ="asd"
        fun load() = File(PATH).readBytes()
        init {
            println("companion object 被加载了")
        }

    }

}

fun main() {
    ConfigMap("a")
}

 

6. 嵌套类 实际上就是 静态内部类 

class Player2 {
     class Equipment(var name: String) {
        fun show() = println("equipment:$name")
    }

    fun battle(){

    }


}


fun main() {
    val equipment = Player2.Equipment("sharp knife")


}

 7. 数据类

data class Coordinate(var x: Int, var y: Int) {
    var isInBounds = x > 0 && y > 0

}

fun main() {
    println(Coordinate(10, 20))
    //== 比较的是内容,equals,Any 默认实现 === ,比较引用
    //=== 比较引用


    println(Coordinate(10, 20) == Coordinate(10, 20))
}

 8.copy函数 数据类专属

data class Student (var name:String,val age:Int){
    private val hobby = "music"
    var subject:String

    init {
        println("initializing student")
        subject = "math"
    }
    constructor(_name:String):this(_name,10)

    override fun toString(): String {
        return "Student(name='$name', age=$age, hobby='$hobby', subject='$subject')"
    }
    constructor(_name:String,_age:Int,_hobby:String,_subject:String):this(_name,10){
        subject=_subject
    }


}

fun main() {
    val s = Student("JACK")

    val copy = s.copy(name = "Rose") //copy只跟主构造函数有关

    println(s)
    println(copy)
}

9.结构声明

class PlayerScore(var experience:Int ,val level :Int,val name:String){
    operator fun component1() = experience  //component后面那个数字必须从1开始
    operator fun component2() = name


}

fun main() {
    /**
     * 普通的结构
     */
   val (x,y) = PlayerScore(10,20,"小智")
    println("$x $y")




}
data class PlayerScore(var experience:Int ,val level :Int,val name:String){
    
}

fun main() {
    /**
     * 数据类自带的结构
     */
   val (x,y) = PlayerScore(10,20,"小智")
    println("$x $y")
}

10. 运算符重载

 data class Coordinate(var x: Int, var y: Int) {
    var isInBounds = x > 0 && y > 0

//    operator fun plus(other:Coordinate):Coordinate {
//        return Coordinate(x+other.x,y+other.y)
//    }
    
    operator  fun  plus(other: Coordinate) = Coordinate(x+other.x,y+other.y)

}

fun main() {

    val c1 = Coordinate(10, 20)
    val c2 = Coordinate(10, 20)

    println(c1+c2)
}

11.枚举类

enum class Direction {
    EAST,
    WEST,
    SOUTH,
    NORTH
}

fun main() {
    println(Direction.EAST)
    println(Direction.EAST is Direction)
}

 11.1 枚举类定义函数

enum class Direction (private val coordinate: Coordinate){
    EAST(Coordinate(1,0)),
    WEST(Coordinate(-1,0)),
    SOUTH(Coordinate(0,-1)),
    NORTH(Coordinate(0,1));


    fun updateCoordinate(playerCoordinate: Direction) =
        Coordinate(playerCoordinate.coordinate.x+coordinate.x,
            playerCoordinate.coordinate.y+coordinate.y)

}

fun main() {
    val updateCoordinate = Direction.EAST.updateCoordinate(Direction.WEST)
    println(updateCoordinate)
}

11.2 代数数据类型

enum class LicenseStatus {
    UNQUALIFIED,
    LEARNING,
    QUALIFIED;

}

class Driver(var status: LicenseStatus) {
    fun checkLicense(): String {
        return when (status) {
            LicenseStatus.UNQUALIFIED -> "没资格"
            LicenseStatus.LEARNING -> "在学"
            LicenseStatus.QUALIFIED -> "有资格"
        }
    }

}

fun main() {
    println(Driver(LicenseStatus.LEARNING).checkLicense())
}

 12.密封类

 

//密封
sealed class LicenseStatus2 {
    object UnQualified : LicenseStatus2(){
        val id :String = "2131"
    }
    object Learning : LicenseStatus2()
    class Qualified(val licenseId: String) : LicenseStatus2()

}

class Driver2(var status: LicenseStatus2) {
    fun checkLicense(): String {
        return when (status) {
            is LicenseStatus2.UnQualified -> "没资格 ${(this.status as LicenseStatus2.UnQualified).id}"
            is LicenseStatus2.Learning -> "在学"
            is LicenseStatus2.Qualified -> "有资格,驾驶证编号 ${(this.status as LicenseStatus2.Qualified).licenseId}"
        }
    }

}



fun main() {
    println(Driver2(LicenseStatus2.UnQualified).checkLicense())
}

相关推荐

  1. Kotlin密封类、类与密封接口的对比分析

    2024-02-21 11:08:03       59 阅读
  2. Kotlin

    2024-02-21 11:08:03       58 阅读
  3. Kotlin语法入门-密封类和密封接口(11)

    2024-02-21 11:08:03       32 阅读
  4. Kotlin 密封类与接口

    2024-02-21 11:08:03       61 阅读
  5. 接口 VS ,如何管理常量?

    2024-02-21 11:08:03       46 阅读
  6. golang接口//结构使用示例

    2024-02-21 11:08:03       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-21 11:08:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-21 11:08:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-21 11:08:03       82 阅读
  4. Python语言-面向对象

    2024-02-21 11:08:03       91 阅读

热门阅读

  1. .net 微服务 服务保护 自动重试 Polly

    2024-02-21 11:08:03       52 阅读
  2. C++ 中的单例模式singleton

    2024-02-21 11:08:03       46 阅读
  3. 设计模式----单例模式

    2024-02-21 11:08:03       45 阅读
  4. 指定截至频率的低通滤波器设计

    2024-02-21 11:08:03       48 阅读
  5. 小程序缓存封装 storage

    2024-02-21 11:08:03       51 阅读
  6. k8s 基础理论

    2024-02-21 11:08:03       42 阅读
  7. 线程相关整理

    2024-02-21 11:08:03       47 阅读