Abstract properties are a feature in Kotlin that allow you to declare properties in an abstract class or interface without providing an immediate implementation. Here's an overview of abstract properties:
1. Definition:
Abstract properties are declared using the `abstract` keyword in abstract classes or interfaces.
2. Purpose:
They define a contract that subclasses must fulfill by providing an implementation for these properties.
3. Usage in abstract classes:
- Can be used with or without a backing field
- Subclasses must override and provide an implementation
4. Usage in interfaces:
- Cannot have a backing field
- Implementing classes must provide an implementation
5. Accessor methods:
You can declare abstract properties with custom getters and setters
Here's an example to illustrate abstract properties:
```kotlin
abstract class Shape {
abstract val area: Double
abstract var name: String
}
class Circle(private val radius: Double) : Shape() {
override val area: Double
get() = Math.PI * radius * radius
override var name: String = "Circle"
}
class Rectangle(private val width: Double, private val height: Double) : Shape() {
override val area: Double
get() = width * height
override var name: String = "Rectangle"
}
fun main() {
val circle = Circle(5.0)
val rectangle = Rectangle(4.0, 3.0)
println("${circle.name} area: ${circle.area}")
println("${rectangle.name} area: ${rectangle.area}")
circle.name = "My Circle"
println("Updated name: ${circle.name}")
}
```
In this example:
- `Shape` is an abstract class with two abstract properties: `area` and `name`
- `Circle` and `Rectangle` are concrete classes that inherit from `Shape`
- They must provide implementations for both `area` and `name`
- `area` is implemented as a read-only property with a custom getter
- `name` is implemented as a mutable property
Abstract properties are useful when you want to ensure that certain properties are present in all subclasses, but the exact implementation may vary depending on the specific subclass.