Start learning free

LESSON 281 OF 671 · FUNCTIONS & CLASSES

Constructors in Java

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object with new. It's used to set up the object's initial state.


  • In Java, a constructor has the same name as the class and no return type:

    class Dog {
        public String name;
        public int age;
    
        public Dog(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    

  • Then create objects with arguments: new Dog("Rex", 4) — the constructor fills in the fields for you.



Full lesson:

In the previous lesson you set fields after creating the object:

Dog dog = new Dog();
dog.name = "Rex";
dog.age = 4;

That works, but it's noisy and easy to forget. Constructors let you initialize the fields the moment new Dog(...) is called.


Defining a constructor

A Java constructor has two distinguishing features:

  • Its name is exactly the class name (Dog for a Dog class).

  • It has no return type — not even void.

public Dog(String name, int age) {
    this.name = name;
    this.age = age;
}

The this keyword

The parameter name and the field name have the same identifier. Without this, both sides of name = name; would refer to the parameter (the local one wins). this is a built-in reference to "the current object", so this.name is the field, and bare name is the parameter.


Calling the constructor

Dog rex  = new Dog("Rex", 4);
Dog luna = new Dog("Luna", 7);

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.


The default constructor

If you don't write any constructor, Java provides a hidden no-arg one for free — that's why new Dog() worked in earlier lessons. The moment you define your own constructor, that freebie disappears: from now on you must call new Dog with the arguments you specified.


Your task

The Dog class already has the name and age fields. Add a constructor that takes a String name and an int age and assigns them using this. Then in mainFunction, create two dogs:

Dog rex  = new Dog("Rex", 4);
Dog luna = new Dog("Luna", 7);

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check