Junior
What is an abstract class and what is it used for?
sobes.tech AI
Answer from AI
An abstract class is a class that contains one or more abstract (without implementation) methods or is declared with the keyword abstract, but does not contain abstract methods. It cannot be instantiated directly.
Usage:
- Defining common behavior: Abstract classes define a skeleton of behavior that must be implemented by its subclasses. This helps avoid code duplication.
- Partial implementation of an interface: Part of the interface can be implemented in an abstract class, leaving specific implementation to subclasses.
- Preventing instantiation: Ensures that only specific subclasses can be created.
abstract class Shape { // Abstract class
abstract fun draw() // Abstract method
fun fill(color: String) { // Regular method
// Implementation of fill
}
}
class Circle : Shape() {
override fun draw() {
// Implementation of circle drawing
}
}