Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method after the constructor has ended

Tags:

java

I need to call a method after the constructor has ended and I have no idea how to do. I have this class:

Class A {
    public A() {
        //...
    }

    public void init() {
        //Call after the constructor
    }
}
like image 307
mikelplhts Avatar asked Dec 12 '14 22:12

mikelplhts


People also ask

What happens if constructor is final?

No, a constructor can't be made final. A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass. The main intention of making a method final would be that the content of the method should not be changed by any outsider.

Can you call a method from a constructor?

A constructor can call methods, yes. A method can only call a constructor in the same way anything else can: by creating a new instance. Be aware that if a method constructs a new object of the same type, then calling that method from a constructor may result in an infinite loop...

Can constructor be overriden?

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.

How are constructors called in Java?

The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.


1 Answers

You either have to do this on the client side, as so:

A a = new A();
a.init();

or you would have to do it in the end of the constructor:

class A {
    public A() {
        // ...
        init();
    }

    public final void init() {
        // ...
    }
}

The second way is not recommended however, unless you make the method private or final.


Another alternative may be to use a factory method:

class A {
    private A() {  // private to make sure one has to go through factory method
        // ...
    }
    public final void init() {
        // ...
    }
    public static A create() {
        A a = new A();
        a.init();
        return a;
    }
}

Related questions:

  • What's wrong with overridable method calls in constructors?
  • Java call base method from base constructor
like image 168
aioobe Avatar answered Oct 20 '22 00:10

aioobe