Junior — Middle
What is the role and purpose of abstract classes in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract classes in object-oriented programming serve as templates for creating other classes. They cannot be instantiated directly and typically contain both implemented methods and abstract (unimplemented) methods that must be overridden in subclasses. This allows defining a common interface and basic behavior while providing flexibility for specific implementations.
Example in Kotlin (Android):
abstract class Animal {
abstract fun makeSound()
fun sleep() {
println("Sleeps")
}
}
class Dog : Animal() {
override fun makeSound() {
println("Bark")
}
}
Here, Animal is an abstract class defining a general contract for all animals, and Dog implements specific sound behavior.