Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Abstract class

Let's explore the concept of abstract classes in Kotlin, their characteristics, and how to use them.

What is an Abstract Class?

An abstract class, in any object-oriented programming language including Kotlin, cannot be instantiated directly. This means you cannot create an object of an abstract class. It is meant to be subclassed by other classes. An abstract class can have both abstract (non-implemented) and non-abstract (implemented) methods.

Characteristics of Abstract Classes:

  • They cannot be instantiated.
  • They can have abstract methods (without implementation) as well as concrete methods (with implementation).
  • They can have properties (variables) with or without initializers.
  • They can have constructors.

Why Use Abstract Classes?

Abstract classes provide a way to:

  • Create a base class with some default implementation that other classes can inherit from.
  • Define a contract (in the form of abstract methods) that the inheriting classes need to fulfill.

Example:

Consider a scenario where you have multiple shapes, and you want to calculate the area of each shape. Here's how you might use an abstract class in Kotlin for this:

  • Defining the Abstract Class:
abstract class Shape {
    abstract fun area(): Double
}
  • Inheriting from the Abstract Class:
class Circle(private val radius: Double) : Shape() {
    override fun area(): Double {
        return Math.PI * radius * radius
    }
}

class Rectangle(private val width: Double, private val height: Double) : Shape() {
    override fun area(): Double {
        return width * height
    }
}
  • Using the Concrete Classes:
fun main() {
    val circle = Circle(5.0)
    println("Area of circle: ${circle.area()}")

    val rectangle = Rectangle(4.0, 7.0)
    println("Area of rectangle: ${rectangle.area()}")
}

Few more things about Abstract Classes in Kotlin:

  • Properties: Abstract classes can have properties, and these properties can be abstract too:
abstract class Shape {
    abstract val name: String
    abstract fun area(): Double
}

class Square(val sideLength: Double) : Shape() {
    override val name: String = "Square"

    override fun area(): Double {
        return sideLength * sideLength
    }
}
  • Constructors: Abstract classes can have constructors (both primary and secondary). Subclasses must call the superclass's constructor when they are instantiated:
abstract class Shape(val color: String) {
    abstract fun area(): Double
}

class Circle(color: String, private val radius: Double) : Shape(color) {
    override fun area(): Double {
        return Math.PI * radius * radius
    }
}
  • Visibility: Abstract members in Kotlin are open by default, meaning they can be overridden by subclasses. Non-abstract members are final by default and need to be explicitly marked as open if you want to allow subclasses to override them.

In conclusion, abstract classes in Kotlin provide a means to define a base blueprint for related classes while leaving some of the specifics (implementation details) to the subclasses.

  1. Kotlin abstract class example: An abstract class in Kotlin is declared using the abstract keyword. It can have both abstract and concrete methods.

    abstract class Shape {
        abstract fun draw()
        fun getColor(): String {
            return "Red"
        }
    }
    
  2. How to create abstract classes in Kotlin: Use the abstract keyword to declare an abstract class. Abstract classes can have both abstract and non-abstract (concrete) methods.

    abstract class Animal {
        abstract fun makeSound()
        fun sleep() {
            println("Zzzzz...")
        }
    }
    
  3. Abstract class constructors in Kotlin: Abstract classes can have constructors, and they can also have primary and secondary constructors.

    abstract class Vehicle(val model: String) {
        abstract fun start()
    }
    
  4. Kotlin abstract class vs regular class: Abstract classes cannot be instantiated, while regular classes can. Abstract classes may have abstract methods that must be implemented by subclasses.

  5. Abstract properties in Kotlin abstract classes: Abstract classes can have abstract properties that must be implemented by subclasses.

    abstract class Shape {
        abstract val area: Double
    }
    
  6. Abstract methods in Kotlin abstract classes: Abstract methods are declared using the abstract keyword and must be implemented by subclasses.

    abstract class Vehicle {
        abstract fun start()
    }
    
  7. Inheritance with Kotlin abstract classes: Subclasses extend abstract classes using the :, and they must provide implementations for abstract methods.

    class Car : Vehicle() {
        override fun start() {
            println("Car started")
        }
    }
    
  8. When to use abstract classes in Kotlin: Use abstract classes when you want to provide a common base with some shared implementation but leave certain methods to be implemented by subclasses.

  9. Kotlin abstract class visibility modifiers: Abstract classes and their members can have visibility modifiers like public, private, protected, etc., controlling access to them.

  10. Abstract class with secondary constructor in Kotlin: Abstract classes can have secondary constructors, providing additional flexibility during instantiation.

    abstract class Shape(val color: String) {
        constructor(color: String, name: String) : this(color)
    }
    
  11. Implementing abstract classes in Kotlin: Subclasses must provide concrete implementations for all abstract methods and properties of the abstract class.

  12. Abstract class and final modifier in Kotlin: Abstract classes can be marked as final to prevent further subclassing.

    final abstract class FinalAbstractClass {
        // ...
    }
    
  13. Abstract class inheritance hierarchy in Kotlin: Abstract classes can be part of an inheritance hierarchy where subclasses extend the abstract class.

    abstract class Animal {
        abstract fun makeSound()
    }
    
    class Dog : Animal() {
        override fun makeSound() {
            println("Woof!")
        }
    }