Kotlin Abstract Class
In Kotlin, an abstract class is a class that cannot be instantiated, but can be subclassed. An abstract class can contain both abstract and non-abstract (concrete) properties and methods. An abstract property or method is a declaration that has no implementation, and must be implemented in the subclass. A concrete property or method has an implementation, and can be used as is, or overridden in the subclass.
To define an abstract class in Kotlin, you use the abstract
modifier in the class declaration. Here's an example of an abstract class:
abstract class Shape { abstract fun area(): Double }
In this example, we define an abstract class called Shape
. The Shape
class has one abstract method called area()
. Since area()
has no implementation, we do not provide a body for it. Any class that inherits from Shape
must provide an implementation for area()
.
Here's an example of a class that inherits from Shape
and provides an implementation for area()
:
class Rectangle(val width: Double, val height: Double) : Shape() { override fun area(): Double { return width * height } }
In this example, we define a class called Rectangle
that inherits from Shape
. We provide the implementation of area()
by multiplying the width
and height
properties of the rectangle.
Note that since Shape
is an abstract class, we cannot create an instance of it directly. However, we can create an instance of Rectangle
, since it provides a concrete implementation of area()
.