What is Kotlin Abstract Class? | Abstract class in Kotlin
What is Kotlin Abstract Class?
In this article, we will cover the following pointers:
- What is an abstract class in kotlin?
- Syntax of an abstract class
- Example of the declaring an abstract class with the abstract member function.
The class defined with the "abstract" keyword is called an abstract class. It cannot be instantiated, which means the user can not create the object of the abstract class. The class members and member functions of the abstract class are non-abstract until and unless declared as abstract. Abstracts class has no meaning standalone, but it is implemented inside the derived class.
Example:
abstract class kotlin_class {
var x = 0
abstract fun member()
}
The member function of an abstract class does not contain its body. The member function can not be declared as abstract if it contains the body.
Example of an abstract class that has an abstract function:
abstract class state{
abstract fun state_name()
}
class Punjab: state(){
override fun state_name(){
println("Punjab is the state....")
}
}
fun main(args: Array<String>){
val obj = state()
obj.state_name();
}
In this example, we have declared the state as an abstract class. state_name() is a member function of the state that is declared as abstract.
Output:
Punjab is the state....
Points to remember about the abstract class:
- It is not possible to create the object of the abstract class.
- All the properties and member functions of the abstract class are by default non-abstract. To make them abstract, declare it with the abstract keyword. If we wish to override the value and member functions in the class, we need to use the open keyword.
- If declared a member function as abstract, then do not need to annotate with the "open" keyword.
- The abstract member function does not have a body inside the abstract class. It is implemented in the derived class.