Ключевое слово extends
В Kotlin для наследования классов и реализации интерфейсов
используется двоеточие : после имени класса.
После двоеточия указывается родительский класс,
а затем через запятую - интерфейсы. Ключевое слово
extends не используется явно, как в некоторых
других языках программирования.
Синтаксис
class ChildClass : ParentClass(), Interface1, Interface2 {
// тело класса
}
Пример
Создадим базовый класс Animal и класс Dog,
который наследует от него:
open class Animal {
fun eat() {
println("Animal is eating")
}
}
class Dog : Animal() {
fun bark() {
println("Dog is barking")
}
}
Теперь создадим объект класса Dog и вызовем методы:
val dog = Dog()
dog.eat()
dog.bark()
Результат выполнения кода:
Animal is eating
Dog is barking
Пример
Наследование с реализацией интерфейсов:
interface Movable {
fun move()
}
interface Soundable {
fun makeSound()
}
open class Vehicle
class Car : Vehicle(), Movable, Soundable {
override fun move() {
println("Car is moving")
}
override fun makeSound() {
println("Car is honking")
}
}
Использование класса Car:
val car = Car()
car.move()
car.makeSound()
Результат выполнения кода:
Car is moving
Car is honking
Пример
Наследование с передачей параметров в конструктор родительского класса:
open class Person(val name: String, val age: Int) {
fun introduce() {
println("My name is $name and I am $age years old")
}
}
class Student(name: String, age: Int, val studentId: String) : Person(name, age) {
fun study() {
println("Student $name is studying")
}
}
Использование класса Student:
val student = Student("John", 20, "S12345")
student.introduce()
student.study()
println("Student ID: " + student.studentId)
Результат выполнения кода:
My name is John and I am 20 years old
Student John is studying
Student ID: S12345