Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an empty constructor from another?

I have some code like so:

public class Foo {
    private int x;

    public Foo() {
    }

    public Foo(int x) {
        try {
            //do some initialisation stuff like:
            this.x = x;
        }
        catch(Exception ge){
            //call empty constructor not possible
            //this();
            //this.EMPTY();
            //Foo();
        }
    }

    public static final Foo EMPTY = new Foo();
}

I'd like to know if it is possible to achieve something such as this (I know that calling another constructor must be the first statement in the constructor). I have looked around here on SO but haven't found anything as such, leading me to believe that perhaps, I ought to handle the error logic in the instantiating method.

like image 303
Dark Star1 Avatar asked Feb 04 '23 05:02

Dark Star1


1 Answers

Just change the execution order :

public class Foo {

    Integer i;
    public Foo() {
        System.out.println("Empty constructor invoked");
    }

    public Foo(Integer i) {

        this(); //can be omitted

        try {
            System.out.println("i initialized to : "+i.toString());

        } catch (Exception ex) {

            System.out.println("i NOT initialized ");
        }
    }


    public static void main(String[] args) {

        new Foo(); //prints: Empty constructor invoked

        new Foo(5);//prints: Empty constructor invoked
                   //prints: i initialized to : 5

        new Foo(null);//prints: Empty constructor invoked
                   //prints: i NOT initialized 
    }
}
like image 71
c0der Avatar answered Feb 06 '23 17:02

c0der