Junior — Middle
In what situations is it preferable to use an abstract class in object-oriented programming?
sobes.tech AI
Answer from AI
An abstract class in object-oriented programming is preferred when you need to define a common interface and base behavior for a group of related classes, but the abstract class itself should not be instantiated directly.
Situations for using an abstract class:
- When there is common functionality that can be implemented once in the base class, and specific details should be implemented in subclasses.
- To ensure that certain methods are overridden in subclasses (via abstract methods).
For example, in Android, you can create an abstract class BaseActivity that contains common methods for all activities, and specific activities will inherit from it and implement their own functionality.