kotlin
  1. kotlin-abstract-class

Kotlin Abstract Class

In Kotlin, an abstract class is a class that cannot be instantiated directly, and is typically used as a base class for other classes. It is a type of class that can have one or more abstract methods and non-abstract methods. In this tutorial, we will look at how to create abstract classes in Kotlin.

Syntax

The syntax for creating an abstract class in Kotlin is:

abstract class ClassName {

    //abstract properties or methods

    //non-abstract properties or methods
}

Example

Here's an example of an abstract class in Kotlin:

abstract class Shape(val name: String) {

    //abstract method
    abstract fun area(): Double

    //non-abstract method
    fun printName() {
        println("The shape is $name")
    }
}

In this example, we have created an abstract class called Shape with an abstract method area() and a non-abstract method printName(). The area() method is not implemented in the abstract class and must be implemented in the classes that inherit from it.

Output

An abstract class cannot be instantiated directly and must be inherited by another class. Therefore, there is no output for an abstract class.

Explanation

An abstract class is similar to a regular class in Kotlin, except that it cannot be instantiated. It can contain abstract and non-abstract methods and properties. An abstract method is a method that does not have a body and must be implemented in the class that inherits from the abstract class. A non-abstract method is a method that has a body and can be used directly without being implemented in the class that inherits from the abstract class.

When creating a subclass of an abstract class, you must implement all the abstract methods in the subclass. If you do not implement all the abstract methods, the subclass itself must be declared as abstract.

Use

An abstract class can be used as a base class for other classes that share a common set of properties and methods. Since an abstract class cannot be instantiated directly, it is often used to define an interface for other classes to implement. This allows for consistency and standardization across related classes.

Important Points

  • An abstract class cannot be instantiated directly.
  • All abstract methods must be implemented in the subclass.
  • A subclass may also be declared abstract if all abstract methods are not implemented.

Summary

In this tutorial, we learned about abstract classes in Kotlin. We covered the syntax, example, output, explanation, use, and important points of abstract classes in Kotlin. With this knowledge, you can now create abstract classes in Kotlin and use them as base classes for other classes.

Published on: