Explain like I'm Five: Constructors in Java

Explain like I'm Five: Constructors in Java

·

3 min read

Let's say you're playing an RPG, like Diablo or World of Warcraft. When you first start you need a character, so you're looking at all the races. Each one of those is a Character, so we'll call our class Character. First we make a java project file, call it whatever you want. I'll call mine Scratch.

class Scratch {
    public static void main(String[] args) {

    }
}

underneath that, we'll write another class called Character.


// The character class for a game of some sort
class Character {

}

It will need some attributes. Every character has to have a name, and maybe a title and some health.

// The character class for a game of some sort
class Character {
        this.name = name;
        this.title = title;
        this.health = health;
}

Now, we want to be able to include these attributes when we make a character, so we will add a constructor so that they have to be initialized at the time you make your character.

A class is a blueprint of an object, so in this case the Character class is the blueprint for any of the characters you want to make. A constructor is the instructions for what the object should come with.

By the way, If you're wondering what this.name or this.title refer to, it refers to the object being made by the class. it means "the name of this object" or "the health of this object".

Lets make the Constructor:

// The character class for a game of some sort
class Character {
        this.name = name;
        this.title = title;
        this.health = health;

        // The constructor of the Character class. This is a set of instructions that says what a new character should come with
        public Character(String name, String title, int health) {
        this.name = name;
        this.title = title;
        this.health = health;
    }

}

Last, lets give our character something to do. We will give him a greeting. underneath the constructor, add this code:

void sayHello() {
        System.out.println("Hello! I'm " + name + "! Henceforth I shall be known as " + title + "! My current health is: " + health);
}

Now all that is left is to make a new character and use the sayhello method. Back at the top of the file, in our scratch class, we add:

class Scratch {
    public static void main(String[] args) {

        Character elfLord = new Character("Rharsgard", "Guardian of the Universe", 999);

        elfLord.sayHello();

    }
}

When you run the file, you should see this:

Hello! I'm Rharsgard! Henceforth I shall be known as Guardian of the Universe! My current health is: 999

To sum up, a constructor is a set of instructions that tells a class what needs to be included when making a new instance of the class. Pretty easy right? If you forget this I'll hunt you down and... Something.