Sobes.tech
Junior

Can constructors be overridden in Java?

sobes.tech AI

Answer from AI

No, constructors are not overridden in Java. Overriding pertains to methods of a subclass that have the same signature (name, return type, and parameter list) as a method in the parent class.

Instead of overriding, constructors in Java use overloading. This means that a class can have multiple constructors with the same name but different parameter lists (different number, types, or order).

A subclass can call the constructors of its parent class using the keyword super(...).

Example of constructor overloading:

class MyClass {
    int value;
    String name;

    // Default constructor
    public MyClass() {
        this.value = 0;
        this.name = "default";
        // Call another constructor using this()
        this(0, "default"); 
    }

    // Overloaded constructor with one parameter
    public MyClass(int value) {
        this.value = value;
        this.name = "default";
    }

    // Overloaded constructor with two parameters
    public MyClass(int value, String name) {
        this.value = value;
        this.name = name;
    }
}