首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Kotlin 面向對象編程詳解(二):屬性、接口、泛型、嵌套類與枚舉

     編輯:Java 相關知識

屬性系統

聲明與可見性

class AttrDemo {
    private var attr1: String = ""
    protected var attr2: String = ""
    // 默認 public
    var attr3: String = ""
    val roAttr: String = "readonly" // 僅 getter
    
    // 自定義訪問器
    var computed: String = ""
        private set // setter 私有
        get() = field.uppercase() // getter 轉大寫
}

空安全強制初始化

  • 非空類型 String 必須在聲明或構造函數中初始化
  • 可空類型 String? 可延遲初始化
  • lateinit var 延遲初始化(非空、非基本類型),訪問前未初始化拋 UEE

接口

定義與實現

interface MyInterface {
    fun method1()          // 抽象方法
    fun method2() { }      // 默認實現
    val prop: Int          // 抽象屬性(需實現類覆寫)
    val constProp = 100    // 編譯期常量
}

class Impl : MyInterface {
    override fun method1() { }
    override val prop: Int = 10
}

接口屬性規則

  • 無後備字段,不能存儲狀態
  • 可聲明抽象屬性或帶默認 getter 的屬性
  • 實現類必須 override 抽象屬性

泛型

類泛型

class Box<T>(val value: T)

// 使用
val intBox = Box(1)        // 類型推導 Box<Int>
val strBox: Box<String> = Box("hello")

型變:in/out

// 協變:只讀生產者
interface Source<out T> { fun next(): T }

// 逆變:只寫消費者
interface Sink<in T> { fun put(value: T) }

// 星投影等價
List<*> ≡ List<out Any?>

實化類型參數

inline fun <reified T> isInstance(value: Any): Boolean = value is T
// 運行時可訪問 T.class,無需傳 Class<T>

嵌套類與內部類

靜態嵌套類

class Outer {
    private val x = 1
    class Nested {        // 無外部類引用
        fun foo() = 2     // 不能訪問 Outer.x
    }
}
val n = Outer.Nested()

內部類

class Outer {
    private val x = 1
    inner class Inner {   // 持有 Outer.this 引用
        fun foo() = x     // 可訪問外部私有字段
    }
}
val i = Outer().Inner()

匿名內部類 / SAM 轉換

// 傳統匿名類
button.setOnClickListener(object : View.OnClickListener {
    override fun onClick(v: View?) { }
})

// SAM 轉換:函數式接口單抽象方法
button.setOnClickListener { startActivity(Intent(this, MVPActivity::class.java)) }

枚舉類

基礎枚舉

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

// 使用
val d = Direction.EAST
val d2 = Direction.valueOf("NORTH")
val all = Direction.values()

帶屬性枚舉

enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}

// 訪問
val redHex = Color.RED.rgb.toString(16).uppercase() // "FF0000"

枚舉實現接口

interface Describable { fun describe(): String }

enum class Status(val code: Int) : Describable {
    SUCCESS(200) { override fun describe() = "成功" },
    FAIL(500) { override fun describe() = "失敗" };
    
    abstract fun describe(): String // 強制每個常量實現
}

完整代碼倉庫

GitHub:helloKotlin | 本站下載:源碼包

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved