Skip to content
Codewilds

Lesson 18 of 34 · Classes & Objects

Java Classes and Objects: Constructors and new

easy10 XP3 min read

So far every value you used had a type Java already knew: int, String, ArrayList. Real programs need their own types — a Hero, an Invoice, a Spaceship. In Java you create new types by writing classes, and this chapter is where your programs start to model the world.

A class is a blueprint; an object is a concrete thing built from that blueprint. One Hero class can produce thousands of heroes, each with its own name and health.

Fields: the data of an object

class Hero {
    String name;
    int level;
    int hp;
}

This class declares three fields (also called instance variables). Every Hero object gets its own copy of all three. You create an object with new and reach its fields with a dot:

Hero aria = new Hero();
aria.name = "Aria";
aria.level = 1;
System.out.println(aria.name + " is level " + aria.level);
Aria is level 1

Fields you don't set get a default value: 0 for numbers, false for booleans and null for object types such as String. In these lessons you write extra classes in the same file as Main — above it and without public, because a file may contain only one public class.

Constructors

Setting every field by hand is tedious and easy to forget. A constructor runs automatically when new creates the object. It has the same name as the class and no return type:

class Hero {
    String name;
    int level;
    int hp;

    Hero(String name, int level, int hp) {
        this.name = name;
        this.level = level;
        this.hp = hp;
    }
}

Hero bram = new Hero("Bram", 5, 140);

this means the object being built. this.name = name; copies the parameter name into the field name — without this., both names would refer to the parameter.

Overloaded constructors and this(...)

A class can have several constructors with different parameter lists — overloading, just like with methods. One constructor can call another with this(...), which must be its very first statement:

Hero(String name) {
    this(name, 1, 100);   // new heroes start at level 1 with 100 HP
}

If you write no constructor at all, Java adds an invisible no-argument constructor — that is why new Hero() worked above. As soon as you declare any constructor yourself, that free one disappears.

Instance methods

Methods without static are instance methods: they belong to an object and can read and change its fields.

void levelUp() {
    level++;
    hp += 10;
}

You call them on a specific object: aria.levelUp(); raises Aria's level and nobody else's. Inside an instance method, level is short for this.level.

References and null

A variable of a class type does not contain the object itself but a reference to it — think of an address.

Hero a = new Hero("Aria");
Hero b = a;              // b points to the SAME hero
b.levelUp();
System.out.println(a.level);
Hero nobody = null;      // refers to no object at all
2

There is only one hero, reachable through two variables. Calling a method on null — nobody.levelUp() — crashes the program with a NullPointerException.

Common mistakes

  • name = name; in a constructor assigns the parameter to itself, so the field stays null. Write this.name = name;.
  • Giving a constructor a return type: void Hero(String name) is an ordinary method, not a constructor, so new Hero("Aria") does not compile.
  • Calling an instance method from main without an object: levelUp(); fails with non-static method cannot be referenced from a static context. Create a hero first and call hero.levelUp().
  • Expecting new Hero() to work after you declared a constructor with parameters.

Assignment

Complete the class Hero (above Main):

  • fields String name, int level and int hp
  • Hero(String name, int level, int hp) — stores the three values
  • Hero(String name) — a new hero at level 1 with 100 HP (call the other constructor with this(...))
  • void levelUp() — adds 1 level and 10 HP
  • void takeDamage(int amount) — subtracts amount from hp, but hp never drops below 0
  • boolean isAlive() — true while hp is greater than 0
  • String describe() — returns text like "Aria (level 1, 100 HP)"
Hero aria = new Hero("Aria");
aria.levelUp();
aria.describe();       // "Aria (level 2, 110 HP)"
aria.takeDamage(500);
aria.isAlive();        // false — hp is 0, not -390

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Classes, objects and structs in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+10 XP

Lesson 18 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.