Junior — Middle
Is it possible to create custom behavior for a constructor in a derived class by overriding it?
sobes.tech AI
Answer from AI
In Java, constructors are not inherited and cannot be overridden in subclasses. Each class must explicitly declare its own constructors. When creating a subclass object, the superclass constructor is called first (explicitly via super() or implicitly), and then the subclass constructor body is executed.
If you need to change the behavior of a constructor in a derived class, you should define a new constructor in the subclass, which can call the superclass constructor and add its own logic:
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
Child() {
super(); // call to the parent constructor
System.out.println("Child constructor");
}
}
Thus, you cannot "override" a constructor, but you can define your own with the desired behavior.