Kotlin Abstraction
Kotlin Abstraction – Abstraction is one of the core concepts of Objected Oriented Programming. When there is a scenario that you are aware of what functionalities a class should have, but not aware of how the functionality is implemented or if the functionality could be implemented in several ways, it is advised to use abstraction. So, when some class extending or implementing this abstraction, they may implement the abstract methods.
Abstraction in Kotlin could be achieved by following ways :
Interfaces
Kotlin Interfaces have similar structure as that of a Kotlin Class, but can contain abstract methods and abstract variables. Which means, the variables of interfaces are not initialized and methods may or may not have implementations. An Interface in Kotlin enforces definite implementations of methods/behaviors/routines in classes that implements the interface.
Following is an example of Kotlin Interface.
interface Vehicle {
var name:String
fun howItRuns()
}
Abstract Classes
An abstract class contains abstract or non-abstract : variables and functions. Abstract Class cannot be initiated but could be extended as a Super Class.
Following is an example of Kotlin Abstract Class.
example.kt
abstract class Vehicle {
// initialized variable
var name : String = "Not Specified"
// abstract variable
abstract var medium : String
// function with body
fun runsWhere() {
println("The vehicle, $name, runs on $medium")
}
// abstract function
abstract fun howItRuns()
}
Differences
Following are some of the differences between Abstract Classes and Interfaces.
Interfaces | Abstract Classes |
Cannot have initialized variables. | Can have initialized variables. |
A single class can implement multiple interfaces. | For a class, only one abstract class could be a super class. |
interface keyword is used to define an interface. | abstract keyword is used to define an abstract class. |
Conclusion
In this Kotlin Tutorial, we have seen in brief the ways of implementing Abstraction in Kotlin. In our following two tutorials, we shall see Kotlin Interfaces and Kotlin Abstract Classes in detail.