В Kotlin суперкласс относится к классу, который расширяется или наследуется другим классом. Суперкласс предоставляет набор методов и свойств, которые может использовать подкласс. Вот некоторые часто используемые методы и примеры:
-
toString():
- Описание: возвращает строковое представление объекта.
- Пример:
open class Vehicle { var brand: String = "" override fun toString(): String { return "Vehicle(brand='$brand')" } } class Car : Vehicle() { // additional properties and methods specific to Car } fun main() { val car = Car() car.brand = "Toyota" println(car.toString()) // Output: Vehicle(brand='Toyota') }
-
равно():
- Описание: сравнивает два объекта на равенство.
- Пример:
open class Person(val name: String, val age: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Person return name == other.name && age == other.age } } fun main() { val person1 = Person("John", 25) val person2 = Person("John", 25) val person3 = Person("Jane", 30) println(person1 == person2) // Output: true println(person1 == person3) // Output: false }
-
hashCode():
- Описание: возвращает значение хеш-кода объекта.
- Пример:
open class Person(val name: String, val age: Int) { override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + age return result } } fun main() { val person = Person("John", 25) println(person.hashCode()) // Output: -1531608865 }
-
Модификатор open():
- Описание: позволяет переопределить метод подклассами.
- Пример:
open class Shape { open fun draw() { println("Drawing a shape.") } } class Circle : Shape() { override fun draw() { println("Drawing a circle.") } } fun main() { val shape: Shape = Circle() shape.draw() // Output: Drawing a circle. }
-
Ключевое слово open():
- Описание: позволяет наследовать класс другим классам.
- Пример:
open class Animal { // properties and methods } class Dog : Animal() { // additional properties and methods specific to Dog } fun main() { val dog = Dog() // Use the Dog class and its superclass methods and properties }