×

java · level 2 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A fills in a new object as it is built.

Remember building new Pet() and then filling in each field, one line at a time? Forget a line, and that field stays empty. A constructor fixes . It runs while new builds the object, so every pet starts complete.

A constructor looks like a method with the class's name and no return type: Pet(String name, int age). Inside, this.name = name; copies the parameter into the field. this means the object being built, so this.name is its field.

Now new Pet("Rex", 3) builds and fills in one go. Leave out an argument, and Java refuses to compile.

public class Main {
    static class Pet {
        String name;
        int age;
        Pet(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    public static void main(String[] args) {
        Pet rex = new Pet("Rex", 3);
        Pet tiddles = new Pet("Tiddles", 5);
        System.out.println(rex.name + " is " + rex.age);
        System.out.println(tiddles.name + " is " + tiddles.age);
    }
}

Once a class has a constructor with parameters, plain new Pet() no longer works.