Sobes.tech
Junior — Middle

In what situations is it recommended to use an abstract class in object-oriented design?

sobes.tech AI

Answer from AI

An abstract class is recommended to be used when you need to define a common template for a group of related classes, but you cannot instantiate the abstract class itself. It allows you to define common methods and fields, as well as declare abstract methods that must be implemented in subclasses.

Use cases:

  • When several classes share common functionality that can be implemented in a base abstract class.
  • When partial implementation is needed, leaving implementation details to subclasses.
  • When a contract needs to be set (via abstract methods), but some common logic should be provided.

Example:

abstract class Animal {
    void breathe() {
        System.out.println("Breathing");
    }
    abstract void makeSound();
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}

Here, Animal is an abstract class with a common implementation of breathing and an abstract method for sound.

In what situations is it recommended to use an… - sobes.tech