Introduction
In this blog, we will look into Kotlin Abstract Class. We will see how an abstract class is defined and how its characteristics can be overridden in its derived classes. We can not make an object of an abstract class, but an object can be formed out of a non-abstract class derived from this class.
If you are new to Kotlin and don’t know how functions are instantiated and used in Kotlin, you can check out our other article on Kotlin Functions.
Abstract Class
An abstract class is used to state some basic characteristics. In Kotlin, an abstract class can not be instantiated. We can not make an object of an abstract class; trying to do the same will lead to a compilation error.
Abstract Class Declaration
To declare an abstract class in Kotlin, we use the abstract keyword.
abstract class class_name{
//body of the class
}
Examples
In this example, we will see how an abstract class can be declared and how a derived class can be made out of an abstract class.
// Creating an abstract class
abstract class GradeSheet(){
// abstract variables
abstract var maths:Int
abstract var english:Int
abstract var science:Int
// abstract method
abstract fun total_marks()
}
// derived class
class Marks(_maths: Int, _english : Int, _science :Int): GradeSheet(){
// overriding the values of abstract variables
override var maths=_maths
override var english=_english
override var science=_science
// overriding the total_marks function to calculate the total
override fun total_marks(){
var total=maths+english+science;
println("Total Marks are: " + total)
}
}
fun main(){
// Making an object of marks class
val ram_marks = Marks(50,89,76)
// Printing the total_marks associated with this object
ram_marks.total_marks();
}
Output:
Total Marks are: 215
There can be both abstract and non-abstract methods and variables in an abstract class. Non-abstract methods or variables can not be overridden in the derived classes. For example,
// Creating an abstract class
abstract class Person(){
// abstract variables
abstract var first_name:String
abstract var last_name:String
abstract var age:Int
// non - abstract method
fun print_info(){ // Can not be overridden in the derived class
println("Name of Person: $first_name $last_name ")
println("Age of Person: $age")
}
}
// derived class
class kid(first_name: String, last_name: String, age: Int) : Person(){
// overriding all the variables
override var first_name = first_name;
override var last_name =last_name;
override var age = age;
}
fun main(){
// Making an object of kid class
val ob1 = kid("Ram", "Kumar", 5)
// Invoking the print_info function
ob1.print_info();
}
Output:
Name of Person: Ram Kumar
Age of Person: 5




