JavaRush /Java Blog /Random EN /Calling a constructor from a constructor
alexnjc
Level 31

Calling a constructor from a constructor

Published in the Random EN group
Often, in order to avoid writing duplicate initialization code, it is necessary to call the code of one constructor from another.
Calling a constructor from a constructor - 1
Here is an example of how this can be done:
public class SomeClass {
  int a;
  int b;
  int c;

public SomeClass(int a, int b){
   this.a = a;
   this.b = b;
  }

public SomeClass(int a, int b, int c){
    // Вызов конструктора с двумя параметрами.
    this(a, b);
    this.c = c;
  }

public void show(){
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);
  }
}
As you can see, for this we use the keyword this, after which we indicate in parentheses the parameters for the corresponding constructor (with two parameters in this case). You can call one constructor from another in the same class, or in a superclass, with the following restrictions:
  • The constructor to be called must be on the first line of code in the calling constructor.
  • A nested constructor cannot have any explicit or implicit reference to "this". So you can't get into the inner class.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION