In this tutorial you will learn about the Kotlin Abstract Class and its application with practical example.
Kotlin Abstract Class
An abstract class is class which can not be instantiate it means you can not create an object of abstract class.However we can inherit them from subclass.
The members of an abstract class are non-abstract if you don’t declare or explicitly use abstract keyword to make them abstract.
Example :-
1 2 3 4 5 6 7 8 9 |
abstract class Employee { var salary: Int = 10000 fun displaySal(sal: Int) { println("My Salary is $sal.") } abstract fun displayJob(description: String) } |
Here , Employee is an abstract class which object can not be created.
Salary is non-abstract property and displaySal is non-abstract method. If you want to override these members so you need to declare them “open”.
displayJob is abstract method. This function must be overridden in subclass,it doesn’t have any implementation
We don’t need to declare abstract class as “open” because abstract classes are always open.
Example: Let’s get understand Kotlin Abstraction by below example. Check below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
abstract class Employee(name : String) { var salary: Int = 10000 init { println("My name is $name.") } fun displaySal(sal: Int) { println("My Salary is $sal.") } abstract fun displayDesignation(description: String) } class EmpDetail(name: String): Employee(name) { override fun displayDesignation(description: String) { println(description) } } fun main(args: Array<String>) { val emp = EmpDetail("W3Add.Com") emp.displayDesignation("I'm a Developer.") emp.displaySal(25000) } |
Output: The output of above code will look like below image.