Codiqo

Learn Java · lesson 38 of 61 · about 8 minutes

Classes, Fields and Constructors

Put tonight's showings on the desk: define your own class with fields and a constructor, and create objects with new.

What you'll learn

  • Define a class with fields
  • Write a constructor
  • Create objects with new

Tonight's showings

The cinema shows Space Pirates at 17:30 and Moon Diner at 20:15. Each showing has the same three facts: a film, a time and how many seats are left. A Showing class describes them once, and new Showing(show, "17:30", 40) makes one showing with its own copy of the fields. When a group books the late showing, only late.seatsLeft goes down; the early showing keeps its 40.

Your own types

A class describes a kind of thing; an object is one of them, created with new. Fields hold each object's data, and a constructor (same name as the class, no return type) sets them up.

this.name = name; means "this object's name field gets the name parameter".

Extra classes can go in the same file as Main, as long as only Main is public.

A pet class

class Pet {
    String name;
    int hunger;

    Pet(String name, int hunger) {
        this.name = name;
        this.hunger = hunger;
    }
}

public class Main {
    public static void main(String[] args) {
        Pet a = new Pet("Phoebe", 2);
        Pet b = new Pet("Rex", 5);
        b.hunger--;
        System.out.println(a.name + " " + a.hunger);
        System.out.println(b.name + " " + b.hunger);
    }
}

Output

Phoebe 2
Rex 4

Tip

Each object has its own copy of the fields. Changing b.hunger has no effect on a.

More than one constructor

A class can have several constructors with different parameters. this(...) as the first line of one constructor calls another, so the setting-up is written once.

A default hunger

class Pet {
    String name;
    int hunger;

    Pet(String name) {
        this(name, 5);
    }

    Pet(String name, int hunger) {
        this.name = name;
        this.hunger = hunger;
    }
}

public class Main {
    public static void main(String[] args) {
        Pet p = new Pet("Phoebe");
        System.out.println(p.name + " " + p.hunger);
    }
}

Output

Phoebe 5

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.