- Published on
OOP Mastery: Inheritance in Kotlin
- Authors
- Name
- Dan Tech
- @dan_0xff
OOP Mastery is a series of self-study articles on Object-Oriented Programming with the Kotlin language, compiled at DanTech0xFF. The purpose of this series of articles is to provide a comprehensive view of Object Orientation in the Kotlin language. This will be a solid foundation for future Programmers if you delve into Android, Mobile Cross Platform, or Backend Java.
- Part 1: OOP Mastery: Types of Classes, Interfaces in Kotlin
- Part 2: OOP Mastery: Encapsulation in Kotlin
- Part 3: OOP Mastery: Inheritance in Kotlin
- Part 4: OOP Mastery: Polymorphism in Kotlin
- Part 5: OOP Mastery: Abstraction in Kotlin
In this article, we will analyze the Inheritance aspect of OOP in the Kotlin programming language.
Recap of Inheritance
Inheritance is the ability to help a Class reuse properties and functions (method, behavior) from another Class.
In this article, I will share in-depth information about inheritance in the Kotlin language.
Inheritance in Kotlin
Inheritance Syntax
Kotlin is strict in determining whether a Class can be inherited. To declare a class that can be inherited, you need to add the keyword open before the class declaration.
open class OpenBaseClass {
private val privateVar = 1
protected val protectedVar = 2
internal val internalVar = 3
val publicVar = 4
private fun privateFunction() {
println("Private Function")
}
protected fun protectedFunction() {
println("Protected Function")
}
internal fun internalFunction() {
println("Internal Function")
}
fun publicFunction() {
println("Public Function")
}
}
class SubClass : OpenBaseClass() {
fun callPrivateVar() {
// Not able to access privateVar
}
fun callPublicVar() {
println(publicVar)
}
fun callProtectedVar() {
println(protectedVar)
}
fun callInternalVar() {
println(internalVar)
}
fun callPrivateFunction() {
// Not able to access privateFunction
}
fun callPublicFunction() {
publicFunction()
}
fun callProtectedFunction() {
protectedFunction()
}
fun callInternalFunction() {
internalFunction()
}
}
Code snippet describing inheritance in OOP Kotlin
Basically, that's all there is to inheritance in Kotlin. The next article will specifically guide you through Polymorphism and Abstraction in Kotlin. Please continue reading!