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?
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.
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.
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.
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.
Sure. If you have a static
function
JSONObject foo(String)
then you can write
public Location(String _Name) throws IOException, JSONException {
this(foo(_Name));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With