BeginnerLesson 7 of 205 min read

Classes and Objects: Fields, Constructors and toString

Learn to define your own types with classes, create objects with constructors, use this, static members, toString and equals, and see object identity against equality in real output.

In this lesson you will

  • Write a class with fields and a constructor
  • Create objects and call methods
  • Use static members
  • Tell identity from equality

About 28 minutes

A Bike is more than a number

So far Hana has used loose numbers: one array for prices, another for ratings, another for names. Keeping them in step is painful, and a Bike should be one thing with a name, a daily price and a status. A class is a blueprint for such a thing. An object is one thing built from the blueprint. Java is built on this idea, and most of what you write from here is classes.

A class has fields, the data each object carries, and methods, the things it can do. A constructor is a special method with the class name and no return type, which runs when you write new and sets the object up. Inside a method, this means the object itself, and you need it when a parameter has the same name as a field. Members marked static belong to the class as a whole, not to any one object, such as a counter of how many bikes were created. Making fields private and exposing methods is called encapsulation, and it lets you change the inside later without breaking the code that uses the class.

Part Purpose
Field Data stored in each object
Constructor Sets up a new object
Method Behaviour of the object
this The current object
static Belongs to the class, shared by all objects
private Hidden from other classes
class Bike {
    private final String name;
    private final int dayPrice;
    private boolean rented;
    private static int created = 0;

    Bike(String name, int dayPrice) {
        this.name = name;
        this.dayPrice = dayPrice;
        created++;
    }
    int priceFor(int days) { return dayPrice * days; }
    void rent() { rented = true; }
    boolean isRented() { return rented; }
    static int getCreated() { return created; }
    @Override public String toString() { return name + " (" + dayPrice + "/day, " + (rented ? "rented" : "free") + ")"; }
    @Override public boolean equals(Object o) {
        return o instanceof Bike b && b.name.equals(name) && b.dayPrice == dayPrice;
    }
    @Override public int hashCode() { return java.util.Objects.hash(name, dayPrice); }
}

public class Main {
    public static void main(String[] args) {
        Bike a = new Bike("City 1", 12);
        Bike b = new Bike("City 1", 12);
        Bike c = a;
        a.rent();
        System.out.println(a);
        System.out.println(b);
        System.out.println("3 days on a: " + a.priceFor(3));
        System.out.println("a == b: " + (a == b) + ", a.equals(b): " + a.equals(b) + ", a == c: " + (a == c));
        System.out.println("c sees the rental too: " + c.isRented());
        System.out.println("bikes created: " + Bike.getCreated());
        Bike none = null;
        System.out.println("null bike: " + none);
        try { none.rent(); } catch (NullPointerException e) { System.out.println("NullPointerException caught"); }
    }
}
City 1 (12/day, rented)
City 1 (12/day, free)
3 days on a: 36
a == b: false, a.equals(b): true, a == c: true
c sees the rental too: true
bikes created: 2
null bike: null
NullPointerException caught

Two objects were created, and the static counter says 2. The toString method controls how an object prints: the first line is “City 1 (12/day, rented)” and the second is “City 1 (12/day, free)”, and the difference is that only bike a was rented. Without a toString method, Java would print only the class name and a hash code. Three days on bike a cost 36, from the price method.

The comparisons show the difference between identity and equality. The operator == asks whether two variables point at the same object. Here a and b are two different objects, so a == b is false, but the equals method that we wrote compares name and price, so a.equals(b) is true. The variable c was set to a, so a == c is true and c is the same bike: renting through a is visible through c, because they are two names for one object. Whenever you override equals you must override hashCode too, with the same fields, so that equal objects land in the same place in hash-based collections, which lesson 10 uses.

The last lines show null, which means that a variable points at no object. Calling a method on null throws a NullPointerException, one of the most common Java errors. The cure is to make sure that variables are set before you use them and to check for null where it is legitimately possible.

Check by hand: 12 x 3 = 36. We made two bikes with new, so the counter is 2, and c = a made no new object.

Do not confuse == and equals

For objects, == compares references and equals compares meaning, if the class defines it. Strings, lists and your own classes need equals.

Make fields private and final when you can

A final field is set once and never changes. Objects that cannot change are easier to reason about and safe to share.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21. The pattern-matching instanceof used in equals needs Java 16 or later.

Practice

Add a method return() that sets rented back to false, and a field for the number of rentals. Print the bike after each change. Then create a Rider class with a name and a list of the bikes they rented, and think about which fields should be private.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is a constructor?

  1. A kind of loop
  2. A type of array
  3. A file
  4. A method that sets up a new object

It has the class name and no return type.

What does this refer to?

  1. The class file
  2. The main method
  3. The current object
  4. The compiler

It resolves name clashes.

Why was a == b false?

  1. Their prices differ
  2. Their names differ
  3. They are different objects
  4. Java is wrong

== compares references.

What must you override together with equals?

  1. main
  2. hashCode
  3. toString only
  4. static

Equal objects need equal hash codes.

What causes a NullPointerException?

  1. Dividing by two
  2. Calling a method on null
  3. Printing text
  4. Using a loop

The variable pointed at no object.

Summary

  • A class defines fields and methods; objects are created with new.
  • Constructors set objects up, and this refers to the current object.
  • == compares identity; equals compares meaning, and hashCode must agree with it.
  • null means no object, and using it causes NullPointerException.

Next lesson

Lesson 8 is the first project: a rental price calculator that uses everything so far.

Questions

What is the difference between a class and an object?

A class is the blueprint. An object is one instance built from it with new.

What does static mean for a field?

There is one copy shared by the whole class instead of one per object.

Do I always need a constructor?

If you write none, Java provides a default one with no parameters. Add your own when objects need setting up.

Progress is saved in this browser.