While you can’t create an object of an abstract class directly, you can define a constructor inside it—and it’s actually quite useful.
🧱 Why define a constructor in an abstract class?
Because when a subclass inherits the abstract class, the constructor of the abstract class is automatically called when the subclass object is created. It allows the abstract class to initialize shared variables or run setup code.
🧪 Example:
abstract class Animal {
Animal() {
System.out.println(“Animal constructor called.”);
}
abstract void sound();
}
class Dog extends Animal {
Dog() {
super(); // This happens automatically even if not written
System.out.println(“Dog constructor called.”);
}
void sound() {
System.out.println("Bark!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
}
}
🖨 Output:
Animal constructor called.
Dog constructor called.
So yes, abstract classes can (and often do) have constructors—they just don’t get used directly by new AbstractClass()
, but they help power what happens behind the scenes when concrete subclasses are instantiated.