Abstract


Method signature

  1. The name of the constructor must be the same as the name of the class
  2. Constructors do not have a return type, not even void
  3. Constructors can have access modifiers

Calling superclass's constructor

super(..) must be the first line inside the subclass’s constructor. This means that if your call to super(..) requires a computed value, the value must be computed inline as arguments to super(..).

Java Default Constructor


  • Java’s default constructor is called implicitly when you don’t define any constructors in your class.

Properties

  • Doesn’t set any fields
  • Calls the super constructor, the default super constructor

Chaining Constructors


// Without chaining constructors
class Circle {
  public Circle(Point c, double r) {
    this.c = c;
    this.r = r;
  }
 
  // Overloaded constructor
  public Circle() {
    this.c = new Point(0, 0);
    this.r = 1;
  }
}
 
 
// Chaining constructors
class Circle {
  public Circle(Point c, double r) {
    this.c = c;
    this.r = r;
  }
 
  // Overloaded constructor with a call to this(..)
  public Circle() {
    this(new Point(0, 0), 1);
  }
}
  • Instead of maintaining two separate constructors, Circle(Point c, double r) and Circle(), we only need to maintain Circle(Point c, double r). This is achieved by chaining the implementation of Circle() to Circle(Point c, double r) using this(new Point(0, 0), 1).

this()

The call to this(..) (if used) must be the first line in the constructor.

You can’t have both super(..) and this(..) in the same constructor.

If you use this(..), the default constructor isn’t automatically added.