Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.2 Constructors — the constructor

Lesson

Setting up a new object

A constructor is a special method that runs automatically when you create an object with new. Its job is to initialize the object — usually to fill in its fields. A constructor has the same name as the class and no return type.


Worked example

class Dog {
    String name;
    int age;

    Dog(String n, int a) {   // constructor: same name as the class
        name = n;
        age = a;
    }
}

Dog d = new Dog("Rex", 3);   // constructor runs, sets the fields

Now d.name is Rex and d.age is 3 the moment the object is built.


▶ Try it: the Dog class has a constructor. Run this, then change the values you pass to new Dog(...) and re-run.



When does a constructor run?


What is a constructor's main job?


The Dog constructor sets name and age. Type what this prints:

Dog d = new Dog("Rex", 3);
System.out.println(d.name);

True or false?