Kotlin Abstract Classes

Kotlin Abstract Classes

Hello fellow coder👋, it's been a while here! I was participating in two hackathons and I have surely learnt a lot in the past week and I will be updating you in the coming blogs. Today, we are learning together about abstract classes.

So before we roll, what are is an abstract class?

image.png In programming languages, an abstract class is a generic class (or type of object) used as a basis for creating specific objects that conform to its protocol, or the set of operations it supports. Abstract classes are not instantiated directly.

Techopedia

And Abstraction ?????

image.png In computer science, abstraction has a similar definition. It is a simplified version of something technical, such as a function or an object in a program. The goal of abstracting data is to reduce complexity by removing unnecessary information.

Kotlin

In Kotlin, an abstract class is declared using the abstract keyword in front of the class. An abstract class can not be instantiated means we can not create objects for the abstract class.
However, you can inherit subclasses from can them.

Example:

abstract class Person {

    var age: Int = 40

    fun displaySSN(ssn: Int) {
        println("My SSN is $ssn.")
    }

    abstract fun displayJob(description: String)
}

Explanation:

🔸 An abstract class Person is created. You cannot create objects of the class.
🔸The class has a non-abstract property age and a non-abstract method displaySSN(). If you need to override these members in the subclass, they should be marked with open keyword.
🔸The class has an abstract method displayJob(). It doesn't have any implementation and must be overridden in its subclasses.

Note: Abstract classes are always open. You do not need to explicitly use open keyword to inherit subclasses from them.

Let's Inherit from the abstract class:

class Teacher(name: String): Person(name) {

    override fun displayJob(description: String) {
        println(description)
    }
}

fun main(args: Array<String>) {
    val jack = Teacher("Jack Smith")
    jack.displayJob("I'm a mathematics teacher.")
    jack.displaySSN(23123)
}s

What's Happening Here:

🔸 Here, a class Teacher is derived from an abstract class Person.

🔸 An object jack of Teacher class is instantiated. We have passed Jack Smith as a parameter to the primary constructor while creating it. This executes the initializer block of the Person class.

🔸 Then, displayJob() method is called using jack object. Note, that the displayJob() method is declared abstract in the base class, and overridden in the derived class.

🔸 Finally, displaySSN() method is called using jack object. The method is non-abstract and declared in Person class (and not declared in Teacher class).

When you run the program, the output will be:

My name is Jack Smith.
I'm a mathematics teacher.
My SSN is 23123.

Points to remember: 📌

🎗 We can’t create an object for abstract class.
🎗 All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword.
🎗 If we declare a member function as abstract then we do not need to annotate with open keyword because these are open by default.
🎗 An abstract member function doesn’t have a body, and it must be implemented in the derived class.

Overriding a non-abstract open member with an abstract one:

In Kotlin we can override the non-abstract open member function of the open class using the override keyword followed by an abstract in the abstract class. Let's implement it using some other example.

open class Livingthings {
    open fun breathe() {
        println("All living things breathe")
    }
}
abstract class Animal : Livingthings() {
    override abstract fun breathe()
}
class Dog: Animal(){
    override fun breathe() {
        println("Dog can also breathe")
    }
}
fun main(args: Array<String>){
    val lt = Livingthings()
    lt.breathe()
    val d = Dog()
    d.breathe()
}

Output:

All living things breathe
Dog can also breathe

Multiple derived classes:

An abstract member of an abstract class can be overridden in all the derived classes. In the program, we override the cal function in three derived class of calculator.

Example of overriding an abstract function in more than one derived class

// abstract class
abstract class Calculator {
    abstract fun cal(x: Int, y: Int) : Int
}
// addition of two numbers
class Add : Calculator() {
    override fun cal(x: Int, y: Int): Int {
        return x + y
    }
}
// subtraction of two numbers
class Sub : Calculator() {
    override fun cal(x: Int, y: Int): Int {
        return x - y
    }
}
// multiplication of two numbers
class Mul : Calculator() {
    override fun cal(x: Int, y: Int): Int {
        return x * y
    }
}
fun main(args: Array<String>) {
    var add: Calculator = Add()
    var x1 = add.cal(4, 6)
    println("Addition of two numbers $x1")
    var sub: Calculator = Sub()
    var x2 = sub.cal(10,6)
    println("Subtraction of two numbers $x2")
    var mul: Calculator = Mul()
    var x3 = mul.cal(20,6)
    println("Multiplication of two numbers $x3")
}

Output:

Addition of two numbers 10
Subtraction of two numbers 4
Multiplication of two numbers 120
Division of two numbers 3

Python Abstract Classes

In Python, we can declare an abstract method by using @abstractmethod decorator.

This abstract method is present in the abc module in python, and hence, while declaring the abstract method, we have to import the abc.

This module provides abstract base classes (abc) that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping

Example:

from abc import abstractmethod
class Vehicle:
    @abstractmethod
    def getNoOfWheels(Self):
        pass

Resources & Notes:

🎈 Geeks For Geeks
🎈 Programmiz
🎈 Kotlin Docs
🎈 Python Docs
🎈 Geeks For Geeks

If you have read up to this point, Kudos to you. In the next article, we will look at interfaces.

Please consider subscribing, sharing or liking this if you have enjoyed my simple article

Ronnie Atuhaire 😎