Middle+
Is there a constructor in an abstract class?
sobes.tech AI
Answer from AI
Yes, an abstract class in Java can have a constructor. Although an abstract class cannot be instantiated directly, its constructor is called when creating an object of a subclass. The constructor of an abstract class is used to initialize common fields and perform shared logic needed by all inheritors.
Example:
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
}
Dog dog = new Dog("Buddy");