![]() |
VOOZH | about |
In Kotlin, an abstract class is a class that cannot be instantiated and is meant to be subclassed. An abstract class may contain both abstract methods (methods without a body) and concrete methods (methods with a body).
An abstract class is used to provide a common interface and implementation for its subclasses. When a subclass extends an abstract class, it must provide implementations for all of the abstract methods defined in the abstract class.
In Kotlin, an abstract class is declared using the abstract keyword in front of the class. An abstract class can not instantiate means we can not create object for the abstract class.
Abstract class declaration:
abstract class ClassName {
// properties and methods here
}
Key Points to remember:
abstract class className(val x: String) { // Non-Abstract Property
abstract var y: Int // Abstract Property
abstract fun method1() // Abstract Methods
fun method2() { // Non-Abstract Method
println("Non abstract function")
}
}
Example: Abstract and Non-Abstract Members -
Output:
Name of the employee: Praveen
Experience in years: 2
Annual Salary: 500000.0
Date of Birth is: 02 December 1994
Explanation: In the above program, Engineer class is derived from the Employee class. An object eng is instantiated for the Engineer class. We have passed two parameters to the primary constructor while creating it. This initializes the non-abstract properties name and experienceof Employee class. The Then employeeDetails() method is called using the eng object. It will print the values of name, experience and the overridden salary of the employee. In the end, dateOfBirth() is called using the eng object and we have passed the parameter date to the primary constructor. It overrides the abstract fun of Employee class and prints the value of passed as parameter to the standard output.
In Kotlin, it’s possible for an abstract class to override a concrete (non-abstract) method from its superclass and make it abstract again. This means the subclass of the abstract class must implement that method.
Example -
Output:
Dog can also breatheAn abstract member of an abstract class can be overridden in all the derived classes. In the program, we overrides the cal function in three derived class of calculator.
Example -
Output:
Addition of two numbers 10
Subtraction of two numbers 4
Multiplication of two numbers 120
Division of two numbers 3
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.