Sobes.tech
Junior — Middle

When is it appropriate to apply an abstract class in object design?

sobes.tech AI

Answer from AI

An abstract class in Java is used when you need to define a common base class with some implementation, but want to prevent direct instantiation of this class.

It is advisable to use an abstract class if:

  • There is common functionality that should be present in all subclasses.
  • You need to declare methods that must be implemented in subclasses (abstract methods).
  • Partial implementation is required, which can be reused.

Example:

abstract class Animal {
    void eat() {
        System.out.println("Eats food");
    }
    abstract void makeSound();
}

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

Here, Animal is an abstract class with a common method eat and an abstract method makeSound, which all animals are required to implement.

When is it appropriate to apply an abstract class in… - sobes.tech