Skip to the workspace
Pebellslearn by building
Classes and Objects  ›  Lesson

Classes and Objects

Classes and Objects 14 minA class describes the fields every object of its kind has, and each use of new with a constructor creates a separate object with its own copy of those fields.

java / Classes and Objects

Explore each scene at your own pace.

01 · The rule

The rule

Classes and Objects

A class describes the fields every object of its kind has, and each use of new with a constructor creates a separate object with its own copy of those fields.

Create independent instances and distinguish shared behavior from per-object state.

So far Brew Bar's drinks have been loose variables: a name here, a price there. With twenty drinks that turns into forty variables and plenty of mix-ups. Java's answer, and the idea the whole language is built around, is to bundle each drink's data into one object made from a class.

The rule

A class is the recipe; each new makes a separate object.

A class describes what every object of its kind holds. A constructor, which has the class's name and no return type, sets up each new object:

public class Drink {
    String name;
    int priceCents;

    Drink(String name, int priceCents) {
        this.name = name;
        this.priceCents = priceCents;
    }
}

An object is one real instance, created with new:

Drink latte = new Drink("Latte", 300);
Drink mocha = new Drink("Mocha", 340);
System.out.println(latte.name);   // Latte
mocha.priceCents = 350;           // changes the mocha only

What to notice:

  • Each object has its own fields. Changing mocha.priceCents leaves latte untouched.
  • this means "the object being built or used". In the constructor, this.name is the field and plain name is the parameter.
  • A class variable holds a reference, like an array variable. Drink favourite = latte; makes a second name for the same object; it does not create a new drink.
  • Unset fields get defaults: 0 for numbers, false for booleans, null for references such as String. (Only local variables are left without a default.)
  • Writing any constructor removes the free one. If you do not write a constructor, Java supplies an empty one that takes no arguments. Once you write Drink(String, int), new Drink() no longer compiles unless you add it yourself.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.