11- Abstract class
11- Abstract class
Points to remember:
1. We can’t create an object for abstract class.
2. All the variables (properties) and member functions of an abstract class are
by default non-abstract. So, if we want to override these members in the
child class then we need to use open keyword.
3. If we declare a member function as abstract then we does not need to
annotate with open keyword because these are open by default.
4. An abstract member function doesn’t have a body, and it must be
implemented in the derived class.
Kotlin
//abstract class
abstract class Employee(val name: String,val experience: Int) { // Non-Abstract
// Property
// Abstract Property (Must be overridden by Subclasses)
abstract var salary: Double
// Non-Abstract Method
fun employeeDetails() {
println("Name of the employee: $name")
println("Experience in years: $experience")
println("Annual Salary: $salary")
}
}
// derived class
class Engineer(name: String,experience: Int) : Employee(name,experience) {
override var salary = 500000.00
override fun dateOfBirth(date:String){
println("Date of Birth is: $date")
}
}
fun main(args: Array<String>) {
val eng = Engineer("Praveen",2)
eng.employeeDetails()
eng.dateOfBirth("02 December 1994")
}
Output:
In Kotlin we can override the non-abstract open member function of the open
class using the override keyword followed by an abstract in the abstract class.
In the below program we will do it. Kotlin program of overriding a non-
abstract open function by an abstract class –
Kotlin
Output:
Kotlin
// abstract class
abstract class Calculator {
abstract fun cal(x: Int, y: Int) : Int
}
// addition of two numbers
class Add : Calculator() {
override fun cal(x: Int, y: Int): Int {
return x + y
}
}
// subtraction of two numbers
class Sub : Calculator() {
override fun cal(x: Int, y: Int): Int {
return x - y
}
}
// multiplication of two numbers
class Mul : Calculator() {
override fun cal(x: Int, y: Int): Int {
return x * y
}
}
fun main(args: Array<String>) {
var add: Calculator = Add()
var x1 = add.cal(4, 6)
println("Addition of two numbers $x1")
var sub: Calculator = Sub()
var x2 = sub.cal(10,6)
println("Subtraction of two numbers $x2")
var mul: Calculator = Mul()
var x3 = mul.cal(20,6)
println("Multiplication of two numbers $x3")
}
Output:
Reference:
A popular book for learning Kotlin is “Kotlin in Action” by Dmitry Jemerov and
Svetlana Isakova. This book provides a comprehensive introduction to the
Kotlin programming language, including its syntax, libraries, and best practices,
with many hands-on examples and exercises.
Similar Reads
Kotlin Nested class and Inner Kotlin Class and Objects
class
Previous Next
Article Contributed By :
Praveenruhil
P Praveenruhil