Skip to Content
Kotlin📘 Ngôn ngữ KotlinKế thừa (Inheritance)

Kế thừa (Inheritance) trong Kotlin

1. Giới thiệu

Kế thừa cho phép class con thừa hưởng thuộc tính và phương thức từ class cha.

2. open và kế thừa

Mặc định class trong Kotlin là final. Dùng open để cho phép kế thừa:

open class Animal(val name: String) { open fun makeSound() { println("$name makes a sound") } } class Dog(name: String) : Animal(name) { override fun makeSound() { println("$name barks") } } fun main() { val dog = Dog("Buddy") dog.makeSound() // Buddy barks }

3. Gọi phương thức cha với super

open class Vehicle(val brand: String) { open fun start() { println("$brand is starting") } } class Car(brand: String) : Vehicle(brand) { override fun start() { super.start() println("Car engine running") } }

4. Override properties

open class Shape { open val sides: Int = 0 } class Triangle : Shape() { override val sides: Int = 3 } class Square : Shape() { override val sides: Int = 4 }

5. Abstract class

abstract class Animal(val name: String) { abstract fun makeSound() fun eat() { println("$name is eating") } } class Cat(name: String) : Animal(name) { override fun makeSound() { println("$name meows") } }

6. Sealed class

sealed class Result { data class Success(val data: String) : Result() data class Error(val message: String) : Result() object Loading : Result() } fun handleResult(result: Result) { when (result) { is Result.Success -> println("Data: ${result.data}") is Result.Error -> println("Error: ${result.message}") Result.Loading -> println("Loading...") } }

7. Constructor và kế thừa

open class Person(val name: String, var age: Int) class Student( name: String, age: Int, val school: String ) : Person(name, age) // Với secondary constructor class Employee : Person { val company: String constructor(name: String, age: Int, company: String) : super(name, age) { this.company = company } }

8. Polymorphism

open class Shape { open fun area(): Double = 0.0 } class Circle(val radius: Double) : Shape() { override fun area() = 3.14159 * radius * radius } class Rectangle(val width: Double, val height: Double) : Shape() { override fun area() = width * height } fun main() { val shapes: List<Shape> = listOf(Circle(5.0), Rectangle(4.0, 3.0)) shapes.forEach { println(it.area()) } }

9. final để ngăn override

open class Parent { open fun method() { println("Parent") } } open class Child : Parent() { final override fun method() { println("Child") } } class GrandChild : Child() { // override fun method() {} // Error! method is final }

10. Any - base class

// Mọi class đều kế thừa Any class MyClass // Ngầm định: class MyClass : Any() // Any có 3 methods: // equals(), hashCode(), toString()

📝 Tóm tắt

  • Dùng open để cho phép kế thừa
  • : thay vì extends
  • override bắt buộc khi ghi đè
  • super gọi phương thức cha
  • abstract cho class/method trừu tượng
  • sealed cho restricted hierarchy
Last updated on