tutorials explain Abstract Classes in Kotlin programming language.
Classes are the basic blocks of any programming language. Classes hold the state and behavior of an entity.
Abstract classes encapsulate abstract high-level behavior, similar to Abstract classes in Java.
The object cannot be created with Abstract classes, Instead, Super classes extend the abstract classes and can create objects.
Abstract classes
- Declared using abstract keyword. The method which contains only the definition, not the implementation
- Contains Abstract methods and non-abstract methods
- Define at least one abstract method
- Class implementing abstract class must provide an implementation for abstract methods
- Used to define a hierarchy of classes for inheritance
- Contains constructors, Init blocks and to initialize fields and properties of a class
Here is an abstract class, abstract and non-abstract members, methods
abstract class AbstractClass {
abstract val abstractmember: Int
abstract fun abstractMethod(parameter: Int): Int
fun notAbstractFun(): String = "Provide impelmentations"
}
Let’s declare an Animal
abstract class
abstract class Animal(_type: String) {
var type: String
abstract var legs: Int
// Initializer Block
init {
this.type = _type
}
// Abstract Methods
abstract fun setLegs(_legs:Int)
abstract fun getLegs():Int
// Non abstract methods
fun getAnimal(){
println("Type :$type")
}
}
Animal
is an abstract class that contains abstract methods.
Creating an instance of Animal using a new operator throws a Cannot create an instance of an abstract class
error.
val animal = Animal("veg")
So, We have to extend to create an object of it.
fun main() {
val lion = Lion("nonveg");
lion.setLegs(4);
var legs = lion.getLegs()
lion.getAnimal();
println("Lion Legs = $legs")
}
class Lion(_type: String): Animal(_type) {
override var legs: Int = 0
override fun setLegs(_legs: Int) {
legs = _legs
}
override fun getLegs():Int {
return legs
}
}
abstract class Animal(_type: String) {
var type: String
abstract var legs: Int
// Initializer Block
init {
this.type = _type
}
// Abstract Methods
abstract fun setLegs(_legs:Int)
abstract fun getLegs():Int
//Non-abstract methods
fun getAnimal(){
println("Type :$type")
}
}
How to create an Instance of an abstract class.
Commonly, Objects can be created using abstract classes. Kotlin allows objects’ Expression syntax to create an instance of an abstract class.
Object expressions are another way to create an instance for single use.
var instance = object: AbstractClass(...){
//...
}
Here is an example
var animal = object: Animal{
override var legs: Int = 0
override fun setLegs(_legs: Int) {
legs = _legs
}
override fun getLegs():Int {
return legs
}
Here is an example