Course outline · 0% complete

0/29 lessons0%

Course overview →

Constructors and this

lesson 5-2 · ~6 min · 14/29

Building objects properly

Setting fields one by one after new is clumsy and error-prone — forget one line and lesson 5-1's defaults leave a null hiding in the object, waiting to crash some later method. Real codebases therefore treat "an object is valid the instant it exists" as a rule. A constructor is a special method that runs during new and sets the object up in one step. It has the same name as the class and no return type:

class Point {
  int x;
  int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

Point p = new Point(3, 4);

this means "the object being built", like Python's self, so this.x = x copies the parameter into the field of the same name. It is the direct translation of Python's __init__.

Once you define any constructor, callers must use it: new Point() stops compiling unless you also define a no-argument constructor.

Code exercise · java

Run this Point class with a constructor and an instance method that uses Math.sqrt. A 3-4-5 triangle checks the math.

Constructors overload too

A class may define several constructors with different parameter lists — the overloading rule from lesson 4-2 applies. A common pattern is a convenience constructor that fills in defaults by delegating to the full one with this(...):

class Point {
  int x;
  int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }

  Point() {
    this(0, 0);   // the origin
  }
}

this(0, 0) calls the other constructor and must be the first line. One warning worth its weight: Java gives you a free no-argument constructor only while you define none yourself — the moment you write Point(int x, int y), plain new Point() stops compiling unless you add it back explicitly, as above.

Quiz

Why does the constructor body say this.x = x instead of just x = x?

Code exercise · java

Your turn. Write a Rectangle class with double fields width and height, a constructor taking both, and two methods: area() and perimeter(). For a 4.0 by 5.0 rectangle print `area: 20.0` and `perimeter: 18.0`.