Sobes.tech
Junior — Middle

Is it possible to call a property setter method before the object constructor finishes?

sobes.tech AI

Answer from AI

In Java, you cannot call a property setter method (setter) before the object constructor has finished executing, if the call is made from outside.

However, inside the constructor, you can call any object methods, including setters. But be cautious: if a setter is overridden in a subclass, calling it from the base class constructor can lead to unexpected behavior, as the subclass may not be fully initialized yet.

Example:

public class Base {
    public Base() {
        setValue(10); // call within constructor
    }
    public void setValue(int val) {
        System.out.println("Base setValue: " + val);
    }
}

public class Derived extends Base {
    private int value;
    @Override
    public void setValue(int val) {
        value = val;
        System.out.println("Derived setValue: " + val);
    }
}

// When creating Derived(), Derived.setValue will be called, but the object is not fully initialized yet

From outside, the object is only accessible after the constructor finishes, so calling a setter before the constructor completes is not possible.