類別
以下是 Kotlin 類別的基本概念: 建構函數(主建構與次建構)、屬性、方法。
1. 類別的基本結構
在 Kotlin 中,類別使用 class
關鍵字定義。
基本語法
class 類別名稱 {
// 屬性
// 方法
}
範例:簡單的類別
class Person {
var name: String = ""
var age: Int = 0
fun introduce() {
println("Hello, my name is $name and I am $age years old.")
}
}
fun main() {
val person = Person()
person.name = "Alice"
person.age = 25
person.introduce() // 輸出:Hello, my name is Alice and I am 25 years old.
}
2. 主建構函數(Primary Constructor)
特性
- 定義於類別名稱的後面,直接初始化屬性。
- 如果類別內需要額外的初始化邏輯,可使用
init
區塊。
語法
class 類別名稱(屬性名稱: 資料型別) {
init {
// 初始化邏輯
}
}
範例
class Person(val name: String, val age: Int) {
init {
println("Initialized with name: $name and age: $age")
}
fun introduce() {
println("Hello, my name is $name and I am $age years old.")
}
}
fun main() {
val person = Person("Bob", 30)
person.introduce()
// 輸出:
// Initialized with name: Bob and age: 30
// Hello, my name is Bob and I am 30 years old.
}
3. 次建構函數(Secondary Constructor)
特性
- 為類別提供額外的建構方式。
- 必須直接(
this
)或間接呼叫主建構函數。 - 使用關鍵字
constructor
定義。
語法
class 類別名稱(val 屬性名稱: 資料型別) {
constructor(次建構參數: 資料型別) : this(主要建構參數) {
// 其他初始化邏輯
}
}
範例
class Person(val name: String, val age: Int) {
constructor(name: String) : this(name, 0) {
println("Secondary constructor called with default age.")
}
fun introduce() {
println("Hello, my name is $name and I am $age years old.")
}
}
fun main() {
val person1 = Person("Alice", 25)
val person2 = Person("Charlie")
person1.introduce() // 輸出:Hello, my name is Alice and I am 25 years old.
person2.introduce() // 輸出:Hello, my name is Charlie and I am 0 years old.
}
4. 屬性(Properties)
- 使用
var
定義可變屬性。 - 使用
val
定義不可變屬性。
class Car(val brand: String, var speed: Int) {
fun accelerate() {
speed += 10
println("$brand is now running at $speed km/h")
}
}
fun main() {
val car = Car("Toyota", 100)
car.accelerate() // 輸出:Toyota is now running at 110 km/h
}
5. 方法(Functions in Classes)
使用 fun
定義方法
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
}
fun main() {
val calc = Calculator()
println(calc.add(3, 5)) // 輸出:8
}