Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Chaining without this()

I understand that constructor chaining goes from the smallest constructor to the biggest. For example

    public MyChaining(){
        System.out.println("In default constructor...");
    }
    public MyChaining(int i){
        this();
        System.out.println("In single parameter constructor...");
    }
    public MyChaining(int i,int j){
        this(j);
        System.out.println("In double parameter constructor...");
    }

Also as I understand that the call to this() and super() must be in the first line. But is it possible (and if yes, is it efficient) to bypass that limit and chain constructors different?

For example I have this two constructors that share some code.

    public Location(String _Name) throws IOException, JSONException {
        //Three lines of unique code (must be executed before the shared code)
        //Shared code
    }

    public Location(JSONObject json) {
        //Shared code
    }

Is it in any way possible for the first constructor to call the second?

like image 455
Akaitenshi Avatar asked Apr 07 '16 13:04

Akaitenshi


People also ask

What does this () mean in constructor chaining?

Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.

How is constructor chaining achieved?

Constructor chaining is the process of calling a sequence of constructors. We can do it in two ways: by using this() keyword for chaining constructors in the same class. by using super() keyword for chaining constructors from the parent class.

Why call to this () must be the first statement in constructor?

Java enforces that the call to super (explicit or not) must be the first statement in the constructor. This is to prevent the subclass part of the object being initialized prior to the superclass part of the object being initialized.

How can constructor chaining be done by using the super keyword?

Constructor Chaining to Another Class in Java To call the constructors in the base class, simply use the statement super() in the constructor of the child class. Just like constructor chaining within the same class, the statement super() should always be the first one in the constructor of your subclass.


Video Answer


1 Answers

Sure. If you have a static function

JSONObject foo(String)

then you can write

public Location(String _Name) throws IOException, JSONException {
    this(foo(_Name));
}
like image 167
Bathsheba Avatar answered Sep 30 '22 11:09

Bathsheba