We have worked with inheritance concepts in Java, c#, and many other languages, but now let’s see how the inheritance concept works with Kotlin. By definition, we all know that inheritance means acquiring some or whole properties of the parent class into the child class.
All classes in Kotlin have a common superclass Any. Like all other OOPs languages, Kotlin also provides this functionality using ” : ” which helps in inheriting child class from the base class.
class Example // Implicitly inherits from Any, we don't have to declare it.
By default, Kotlin classes are final, they can’t be inherited therefore we need to use the keyword “open” in front of the class declaration to make it inheritable just like we use public in case of inheritance in Java. Have a look at the below-mentioned code.
open class Parent //Class is allowed for inheritance
Let us see a below simple code which shows how inheritance will work:-
open class Parent {
open val vertexCount: Int = 0
}
class Child : Parent() {
override val vertexCount = 4
}
The concept of inheritance allows code reusability. A derived class has only one base class and can have multiple interfaces, whereas a base class may have one or more child classes.
This is a basic implementation of inheritance in Kotlin, in next upcoming post we will be getting in depth of inheritance in kotlin.
Feel free to read and comment below.
Below is my android application, and is useful for people who has Google Opinion Rewards to cash out.
https://play.google.com/store/apps/details?id=com.manasvi.sawant.rewardtocash
If you wanted to create a website, please visit my fiverr gig link below or contact me on support@techoceanhub.com.