Explain Inheritance in Kotlin | Kotlin Tutorial
Jan 21, 2022
#KotlinLanguage #Programming,
1841 Views
In this article, we will learn about the following:What is inheritance?Example of inheritance
Explain Inheritance in Kotlin | Kotlin Tutorial
In this article, we will learn about the following:
- What is inheritance?
- Example of inheritance
What is Inheritance?
Inheritance is one of the crucial concepts of Object-Oriented language. Inheritance means extending the behavior of one class to another class. In a simple language, it means to inherit the features of an existing class to another class.
There are two types of classes involved in inheritance.
- Super Class: It's the main class or parent class from which properties have been inherited to another class.
- Sub Class: It is the class in which properties inherit.
Inheritance allows inheriting the properties of multiple classes into another class.
Syntax:
open class Base(p: Int){
# class properties
}
class Derived(p: Int) : Base(p){
#class properties
}
Example of inheritance
open class A(name: String, age: Int, salary: Float) {
// code of employee
}
class B(name: String, age: Int, salary: Float): A(name,age,salary) {
// code of programmer
}
class C(name: String, age: Int, salary: Float): A(name,age,salary) {
// code of salesman
}
Points to Remember:
- If we want to inherit any class, use the open keyword before the class keyword.
- All the kotlin classes are final by nature, due to which we have to use the open keyword to make it non-final.
- Child classes can inherit variables and methods of the parent class.
- Child class should have only one parent class, but the parent class can have multiple child classes.