Explain like I'm Five: Constructors in Java

Explain like I'm Five: Constructors in Java

drew's photo
·May 8, 2022·

1 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

// The class of person
class Character {

// You want your character to have a name, maybe a title like OrcSlayer. 
//And maybe he or she has health.

    String name;
    String title;
    int health;

// You want to be able to make your character with these things, 
//so you make a constructor that will include them when you make your character

   public Character(String name, String title, int health) {
        this.name = name;
        this.title = title;
        this.age = age;
// the keyword 'this' refers to this object, the class

Now when you make a new character, you can include the attributes.

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

        Character character = new Character("Rharsgard", "Guardian of the Universe", 999); // Because who doesn't want to be Guardian of the universe?

// Then you can use the character Lets give it something to say.

     void sayHello() {
           System.out.println("Hello! I'm  " + name + ", " title + "! Fear me!");
Share this