Sobes.tech
Junior — Middle

Is it possible to define a constructor inside an abstract class?

sobes.tech AI

Answer from AI

Yes, in Java, it is possible to define a constructor within an abstract class. Although an abstract class cannot be instantiated directly, its constructor is called when creating objects of subclasses.

This is useful for initializing common fields or performing shared logic when creating instances of inheriting classes.

Example:

public abstract class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public abstract void makeSound();
}

public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    @Override
    public void makeSound() {
        System.out.println(name + " says: Woof!");
    }
}

Here, the constructor of the abstract class Animal is called from the constructor of the subclass Dog.

Is it possible to define a constructor inside an… - sobes.tech