Interface trong Kotlin
🎯 Mục tiêu: Hiểu Interface - contract định nghĩa hành vi, với default implementations.
💡 Khái niệm
Interface định nghĩa contract (tập hợp methods/properties) mà class phải implement.
interface Clickable {
fun click()
}
class Button : Clickable {
override fun click() {
println("Button clicked!")
}
}📝 Interface với Default Implementation
interface Clickable {
fun click() // Abstract - bắt buộc implement
fun showOff() = println("I'm clickable!") // Default implementation
}
class Button : Clickable {
override fun click() {
println("Button clicked")
}
// showOff() đã có default, không cần override
}🔧 Multiple Interfaces
interface A {
fun foo() = println("A")
}
interface B {
fun foo() = println("B")
}
class C : A, B {
override fun foo() {
super<A>.foo() // Gọi A.foo()
super<B>.foo() // Gọi B.foo()
}
}📦 Interface Properties
interface User {
val name: String // Abstract property
val email: String
get() = "$name@example.com" // Default implementation
}
class AdminUser(override val name: String) : User
// email tự động có giá trị "[email protected]"🎯 Interface vs Abstract Class
| Interface | Abstract Class |
|---|---|
| Không có state | Có thể có state |
| Multiple inheritance | Single inheritance |
| Không có constructor | Có constructor |
✅ Checklist
- Tạo interface với abstract methods
- Sử dụng default implementation
- Implement multiple interfaces
- Phân biệt interface vs abstract class
Tiếp theo: Extension Functions
Last updated on