Site Search:

Create and overload constructors; including impact on default constructors


Back OCAJP



A constructor is used to instantiate a new instance of a class, constructor has no return type, the constructor name matches exactly the class name. Constructor can be omitted, when it is omitted, JVM will create a default no parameter constructor for you. You can overload constructors with different parameters. You can call other constructor inside a constructor with this(parameter list); Whenever this(parameter list) is called, it has to be the first line in the constructor.

======
OCAJP>cat test.java 
class test{
  String a;
  final int b;
  public static void main(String...args) {
    test t = new test("string only");
    System.out.println(t.a + t.b);
    t = new test(8);
    System.out.println(t.a + t.b);
    t = new test("test", 5);
    System.out.println(t.a + t.b);
    //t = test();  //error: method test in class test cannot be applied to given types
  }
  
  public test(String a, int b) {
    this.a = a;  //this.variableName is refer to instance variable
    this.b = b;
  }
  public test(String a) {
    //System.out.println();  //error: call to this must be first statement in constructor
    this(a, 0);
  }
  public test(int b) {
    this("string", b);
  }
}  
OCAJP>javac test.java 
OCAJP>java test
string only0
string8
test5
====== OCA test tracing code flow, so we need to know the order of initialization.
initialize superclass firstly, then static variable and static initializers from top down, then instance variable and instance initializers from top down, finally, the constructor.

======
OCAJP>cat test.java 
class test{
  String a;
  final int b;
  static boolean choice = true;
  static {
    choice = false;
    System.out.println(choice);
  }
  public static void main(String...args) {
    test t = new test("string only");
    System.out.println(t.a + t.b);
  }
   
  {
    a = "in instance initializer";
    System.out.println(a);
  }

  
  
  public test(String a, int b) {
    this.a = a;  //this.variableName is refer to instance variable
    this.b = b;
    System.out.println("in constructor public test(String a, int b)");
  }
  public test(String a) {
    //System.out.println();  //error: call to this must be first statement in constructor
    this(a, 0);
    System.out.println(a);
  }
  public test(int b) {
    this("string", b);
  }
}  
OCAJP>javac test.java 
OCAJP>java test
false
in instance initializer
in constructor public test(String a, int b)
string only
string only0
======
Back OCAJP