Junior — Middle
Explain what an abstract class in object-oriented programming is.
sobes.tech AI
Answer from AI
An abstract class in object-oriented programming is a class that is not intended to be instantiated directly. It serves as a base template for other classes and can contain:
- Abstract methods — declared but not implemented in the abstract class itself, and must be implemented in subclasses.
- Regular methods with implementations, which can be used or overridden in inheriting classes.
An abstract class helps define a common interface and behavior for a group of related classes, while allowing for specific implementations in subclasses.
Example in Java:
abstract class Animal {
abstract void makeSound(); // abstract method
void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
Here, Animal cannot be instantiated directly, but Dog, which implements the abstract method, can be.