Class và Object trong Kotlin
1. Giới thiệu
Kotlin là ngôn ngữ OOP, mọi thứ đều liên quan đến class và object.
2. Khai báo Class
class Person {
var name: String = ""
var age: Int = 0
fun introduce() {
println("Tôi là $name, $age tuổi")
}
}
fun main() {
val person = Person()
person.name = "Alice"
person.age = 25
person.introduce()
}3. Primary Constructor
class Person(val name: String, var age: Int) {
fun introduce() {
println("Tôi là $name, $age tuổi")
}
}
fun main() {
val person = Person("Bob", 30)
println(person.name) // Bob
person.age = 31 // Có thể thay đổi vì var
}4. init Block
class Person(val name: String) {
val nameLength: Int
init {
nameLength = name.length
println("Person created: $name")
}
}
fun main() {
val p = Person("Alice") // In: Person created: Alice
println(p.nameLength) // 5
}5. Secondary Constructor
class Person {
var name: String
var age: Int
constructor(name: String) {
this.name = name
this.age = 0
}
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
}
fun main() {
val p1 = Person("Alice")
val p2 = Person("Bob", 30)
}6. Properties
class Rectangle(val width: Double, val height: Double) {
// Computed property
val area: Double
get() = width * height
// Property với backing field
var color: String = "white"
set(value) {
field = value.lowercase()
}
get() = field.uppercase()
}
fun main() {
val rect = Rectangle(5.0, 3.0)
println(rect.area) // 15.0
rect.color = "RED"
println(rect.color) // RED
}7. Visibility Modifiers
class BankAccount(private val accountNumber: String) {
private var balance = 0.0
fun deposit(amount: Double) {
if (amount > 0) balance += amount
}
fun getBalance() = balance
}
// public - mặc định, visible everywhere
// private - chỉ trong class
// protected - class và subclasses
// internal - trong cùng module8. Member Functions
class Calculator {
fun add(a: Int, b: Int) = a + b
fun subtract(a: Int, b: Int) = a - b
fun multiply(a: Int, b: Int) = a * b
fun divide(a: Int, b: Int) = if (b != 0) a / b else null
}
fun main() {
val calc = Calculator()
println(calc.add(5, 3)) // 8
}9. Companion Object
class User private constructor(val name: String) {
companion object {
fun create(name: String): User {
println("Creating user: $name")
return User(name)
}
const val MAX_AGE = 150
}
}
fun main() {
val user = User.create("Alice")
println(User.MAX_AGE) // 150
}10. Late Initialization
class MyClass {
lateinit var name: String
fun initialize() {
name = "Initialized"
}
fun checkInit() {
if (::name.isInitialized) {
println(name)
}
}
}📝 Tóm tắt
class ClassNamekhai báo class- Primary constructor trong header
initblock cho initialization logicvalread-only,varmutable- Visibility: public, private, protected, internal
companion objectcho static-like members
Last updated on