TExcelTAD
Home › Java › Java Classes/Objects

Java Classes and Objects

Everything in Java is built around classes. In this chapter you'll define your own classes, create objects from them, and see what really happens when you assign one object variable to another.

Defining a class

A class declaration uses the keyword class followed by a name in PascalCase. Inside the braces you list its fields (data) and methods (behaviour):

java · try it yourself
class Book {
    String title;
    String author;
    int pages;

    void describe() {
        System.out.println(title + " by " + author + " (" + pages + " pages)");
    }
}

class Main {
    public static void main(String[] args) {
        Book b = new Book();
        b.title = "Dune";
        b.author = "Frank Herbert";
        b.pages = 412;
        b.describe();
    }
}
Dune by Frank Herbert (412 pages)

Creating objects

new Book() does three things: allocates memory for a new object, sets every field to its default value, and returns a reference to the object. The variable b stores that reference.

You access fields and methods with the dot operator: b.title, b.describe().

Multiple objects

Every object has its own set of field values. Changing one object doesn't affect another:

java · try it yourself
class Counter {
    int value;

    void increment() {
        value++;
    }
}

class Main {
    public static void main(String[] args) {
        Counter clicks = new Counter();
        Counter visits = new Counter();
        clicks.increment();
        clicks.increment();
        clicks.increment();
        visits.increment();
        System.out.println("clicks = " + clicks.value);
        System.out.println("visits = " + visits.value);
    }
}
clicks = 3
visits = 1

Default field values

Unlike local variables, fields are initialised automatically if you don't give them a value:

java · try it yourself
class Settings {
    int volume;
    double brightness;
    boolean darkMode;
    String language;
}

class Main {
    public static void main(String[] args) {
        Settings s = new Settings();
        System.out.println(s.volume);
        System.out.println(s.brightness);
        System.out.println(s.darkMode);
        System.out.println(s.language);
    }
}
0
0.0
false
null

References: two variables, one object

Object variables hold references. Assigning one to another copies the reference, not the object — both variables then point to the very same object:

java · try it yourself
class Point {
    int x, y;
}

class Main {
    public static void main(String[] args) {
        Point a = new Point();
        a.x = 1;
        a.y = 2;

        Point b = a;          // b refers to the SAME object as a
        b.x = 100;
        System.out.println("a.x = " + a.x);
        System.out.println("a == b: " + (a == b));

        Point c = new Point();
        c.x = 100;
        c.y = 2;
        System.out.println("a == c: " + (a == c));   // equal values, different objects
    }
}
a.x = 100
a == b: true
a == c: false

== on objects checks whether two references point to the same object, not whether their contents are equal.

Objects and null

A reference variable can hold null, meaning "no object". Calling a method or reading a field through null causes a NullPointerException:

java · try it yourself
class Book {
    String title = "Untitled";
}

class Main {
    public static void main(String[] args) {
        Book b = null;
        if (b == null) {
            System.out.println("No book yet");
        }
        b = new Book();
        System.out.println(b.title);
        try {
            Book missing = null;
            System.out.println(missing.title);
        } catch (NullPointerException e) {
            System.out.println("Caught a NullPointerException");
        }
    }
}
No book yet
Untitled
Caught a NullPointerException

Note: Objects that are no longer referenced by any variable are cleaned up automatically by the garbage collector. There is no delete in Java.

One class per file

In real projects each public class lives in its own file named after the class (Book.java, Counter.java), and they find each other because they're in the same package. Our playgrounds keep several classes in one file for convenience, which is perfectly legal as long as at most one is public.

Test yourself

What is the default value of an uninitialised String field?

  1. ""
  2. "null"
  3. null
  4. It won't compile

After Point a = new Point(); Point b = a; b.x = 5; what is a.x?

  1. 0
  2. 5
  3. null
  4. Compile error

What does obj1 == obj2 compare for objects?

  1. All field values
  2. The class names
  3. Whether both refer to the same object
  4. The hash codes as strings