Kotlin Abstract Classes 🎯

beginner
13 min

Kotlin Abstract Classes 🎯

Welcome to this comprehensive guide on Kotlin Abstract Classes! In this tutorial, we'll learn about abstract classes, their importance, and how to use them in your projects. Let's dive in!

Introduction to Abstract Classes 📝

Abstract classes are a type of class in Kotlin that cannot be instantiated directly. They are used as a base for other classes, providing a common structure or shared functionality.

Why Abstract Classes? 💡

  • They allow us to define common methods and properties across multiple classes.
  • They can contain abstract methods, which must be implemented by any concrete subclass.
  • Abstract classes can enforce a minimum set of functionality that all subclasses must inherit.

Creating an Abstract Class ✅

To create an abstract class, you use the abstract keyword before the class name. Here's an example of an abstract class named Animal.

kotlin
abstract class Animal

Abstract Methods 💡

Abstract methods are methods that are declared but not implemented in an abstract class. They must be implemented by any concrete subclass. To declare an abstract method, use the abstract keyword before the method definition.

kotlin
abstract class Animal { abstract fun sound(): String }

In this example, the sound() method is an abstract method that needs to be implemented by any subclass of Animal.

Creating a Concrete Subclass 📝

To create a concrete subclass, you can extend the abstract class and implement the abstract methods. Here's an example of a Dog class that extends Animal and implements the sound() method.

kotlin
class Dog : Animal() { override fun sound(): String { return "Woof!" } }

Accessing Abstract Methods 💡

You can call abstract methods on an instance of a concrete subclass. Here's how to call the sound() method on a Dog instance.

kotlin
val myDog = Dog() println(myDog.sound()) // Output: Woof!

Abstract Properties 💡

Just like abstract methods, you can also define abstract properties in an abstract class. Abstract properties are properties without an initial value and must be implemented by any concrete subclass.

kotlin
abstract class Animal { abstract var legs: Int } class Dog : Animal() { override var legs = 4 }

In this example, the legs property is an abstract property that needs to be implemented by any subclass of Animal.

Quiz 🎯

Question: Which keyword is used to create an abstract class in Kotlin?

A: abstact B: abstract C: interfaces

Correct: B Explanation: In Kotlin, the abstract keyword is used to create an abstract class.


Now that you've learned about abstract classes, let's move on to creating a more complex example in our next lesson! Happy coding! 🚀