In this tutorial you will learn about the Kotlin Inheritance and its application with practical example.
Kotlin Inheritance
Inheritance is mechanism in which child class aquires all the properties and behaviors of parent class.It represent IS-A relationship. Inheritance is used to achieve Method Overriding and Code Reusability.
Syntax of Inheritance in Kotlin:
1 2 3 |
class Child : ParentClass(){ } |
Example: In below example we have created two class one is Parentclass and ChildClass. We will use Parentclass function in child class.
ParentClass.kt : Here created welcome function and define class as open so that we can use it in child class.
1 2 3 4 5 |
open class ParentClass{ fun welcome(){ print("Welcome to W3Adda.com, Parent Class") } } |
ChildClass.kt: Here we have extend ParentClass so that we can use it in this class.
1 2 3 4 5 6 7 8 9 |
class ChildClass: ParentClass() { } fun main(args: Array<String>) { var a = ChildClass() a.welcome() } |
Output: Output of this code will look like below image, It prints the ParentClass.kt’s welcome function which is called by our child class.