Junior — Middle
Explain what an abstract class is and how it differs from a regular class.
sobes.tech AI
Answer from AI
An abstract class is a class that is not intended to be instantiated directly. Its main purpose is to serve as a base for other classes. An abstract class can contain abstract methods — methods without implementation that must be implemented in subclasses.
Differences from a regular class:
- You cannot create an object of an abstract class directly.
- It can contain abstract methods.
- It is used to define a common interface and behavior for a group of subclasses.
Example in Kotlin (Android):
abstract class Animal {
abstract fun makeSound()
fun sleep() {
println("Sleeps")
}
}
class Dog : Animal() {
override fun makeSound() {
println("Bark")
}
}
fun main() {
val dog = Dog()
dog.makeSound() // Outputs: Bark
dog.sleep() // Outputs: Sleeps
}