Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and functions from another class. In Kotlin, inheritance promotes code reusability and establishes a hierarchical relationship between classes.
In Kotlin, the class being inherited from is called the superclass or base class, and the class that inherits is called the subclass or derived class.
By default, all classes in Kotlin are final, meaning they cannot be inherited. To allow a class to be inherited, it must be marked with the open keyword.
open class Animal {
fun eat() {
println("Eating...")
}
}
To inherit a class, use the colon (:) symbol followed by the superclass name.
class Dog : Animal() {
fun bark() {
println("Barking...")
}
}
If the superclass has a primary constructor, the subclass must initialize it using the super keyword.
open class Person(val name: String)
class Student(name: String, val studentId: Int) : Person(name)
If the subclass has a secondary constructor, it must delegate to the primary constructor of the superclass.
open class Person(val name: String)
class Student : Person {
constructor(name: String, val studentId: Int) : super(name)
}
To allow a method to be overridden, mark it with the open keyword. The subclass can then override it using the override keyword.
open class Animal {
open fun sound() {
println("Animal makes a sound")
}
}
class Dog : Animal() {
override fun sound() {
println("Dog barks")
}
}
Similar to methods, properties can be overridden. A val property can be overridden by another val or a var, but a var cannot be overridden by a val.
open class Shape {
open val sides: Int = 0
}
class Triangle : Shape() {
override val sides: Int = 3
}
The super keyword is used to call the superclass's methods or access its properties.
open class Animal {
open fun sound() {
println("Animal makes a sound")
}
}
class Dog : Animal() {
override fun sound() {
super.sound()
println("Dog barks")
}
}
When creating an instance of a subclass, the initialization process follows this order:
open class Base(val name: String) {
init {
println("Initializing Base")
}
}
class Derived(name: String) : Base(name) {
init {
println("Initializing Derived")
}
}
An abstract class cannot be instantiated and may contain abstract members that must be implemented by subclasses.
abstract class Animal {
abstract fun sound()
}
class Dog : Animal() {
override fun sound() {
println("Dog barks")
}
}
Kotlin supports multiple inheritance through interfaces. An interface can contain abstract methods and properties, as well as method implementations.
interface Animal {
fun sound()
}
interface Pet {
fun play()
}
class Dog : Animal, Pet {
override fun sound() {
println("Dog barks")
}
override fun play() {
println("Dog plays fetch")
}
}
Sealed classes are used to represent restricted class hierarchies, where a value can have one of the types from a limited set.
sealed class Result
class Success(val data: String) : Result()
class Error(val error: String) : Result()
Inheritance in Kotlin provides a powerful mechanism to build upon existing code, promoting reusability and a clear hierarchical structure. By understanding and applying the principles of inheritance, constructors, method overriding, and interfaces, you can design robust and maintainable Kotlin applications.
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and functions from another class. In Kotlin, inheritance promotes code reusability and establishes a hierarchical relationship between classes.
In Kotlin, the class being inherited from is called the superclass or base class, and the class that inherits is called the subclass or derived class.
By default, all classes in Kotlin are final, meaning they cannot be inherited. To allow a class to be inherited, it must be marked with the open keyword.
open class Animal { fun eat() { println("Eating...") } }
To inherit a class, use the colon (:) symbol followed by the superclass name.
class Dog : Animal() { fun bark() { println("Barking...") } }
If the superclass has a primary constructor, the subclass must initialize it using the super keyword.
open class Person(val name: String) class Student(name: String, val studentId: Int) : Person(name)
If the subclass has a secondary constructor, it must delegate to the primary constructor of the superclass.
open class Person(val name: String) class Student : Person { constructor(name: String, val studentId: Int) : super(name) }
To allow a method to be overridden, mark it with the open keyword. The subclass can then override it using the override keyword.
open class Animal { open fun sound() { println("Animal makes a sound") } } class Dog : Animal() { override fun sound() { println("Dog barks") } }
Similar to methods, properties can be overridden. A val property can be overridden by another val or a var, but a var cannot be overridden by a val.
open class Shape { open val sides: Int = 0 } class Triangle : Shape() { override val sides: Int = 3 }
The super keyword is used to call the superclass's methods or access its properties.
open class Animal { open fun sound() { println("Animal makes a sound") } } class Dog : Animal() { override fun sound() { super.sound() println("Dog barks") } }
When creating an instance of a subclass, the initialization process follows this order:
open class Base(val name: String) { init { println("Initializing Base") } } class Derived(name: String) : Base(name) { init { println("Initializing Derived") } }
An abstract class cannot be instantiated and may contain abstract members that must be implemented by subclasses.
abstract class Animal { abstract fun sound() } class Dog : Animal() { override fun sound() { println("Dog barks") } }
Kotlin supports multiple inheritance through interfaces. An interface can contain abstract methods and properties, as well as method implementations.
interface Animal { fun sound() } interface Pet { fun play() } class Dog : Animal, Pet { override fun sound() { println("Dog barks") } override fun play() { println("Dog plays fetch") } }
Sealed classes are used to represent restricted class hierarchies, where a value can have one of the types from a limited set.
sealed class Result class Success(val data: String) : Result() class Error(val error: String) : Result()
Inheritance in Kotlin provides a powerful mechanism to build upon existing code, promoting reusability and a clear hierarchical structure. By understanding and applying the principles of inheritance, constructors, method overriding, and interfaces, you can design robust and maintainable Kotlin applications.
Companion objects hold static members, like Java’s static methods, in Kotlin classes.
A concise way to define anonymous functions using { parameters -> body } syntax.
Kotlin prevents null pointer exceptions using nullable (?) and non-null (!!) type syntax.
Inline functions reduce overhead by inserting function code directly at call site.
JetBrains, the makers of IntelliJ IDEA, developed Kotlin and released it in 2011.
Allows non-null variables to be initialized after declaration (used with var only).
val is immutable (read-only), var is mutable (can change value).
Compiler automatically determines variable types, reducing boilerplate code.
A data class automatically provides equals(), hashCode(), toString(), and copy() methods.
A function that takes functions as parameters or returns them.
Kotlin is a modern, statically typed language that runs on the Java Virtual Machine (JVM).
They add new methods to existing classes without modifying their source code.
It allows unpacking data class properties into separate variables.
== checks value equality; === checks reference (memory) equality.
apply is a scope function to configure an object and return it.
A class that restricts subclassing, useful for representing restricted class hierarchies.
Coroutines enable asynchronous programming by suspending and resuming tasks efficiently.
Functions can define default values for parameters, avoiding overloads.
Kotlin offers concise syntax, null safety, and modern features not found in Java.
Kotlin automatically casts variables to appropriate types after type checks.
Use the object keyword to create a singleton.
Calls a method only if the object is non-null.
Yes, Kotlin supports backend development using frameworks like Ktor and Spring Boot.
Data structures like List, Set, and Map, supporting functional operations.
Copyrights © 2024 letsupdateskills All rights reserved