Skip to content

Reading, writing and initializing fields

โ˜• Java 17 ยท Bringing Your Class to Life: Creating Objects ยท 2/3

new gives you a reference to a fresh object. The dot lets you reach the object's fields through that reference.

Dot notation

public class Movie {
    String title;
    int releaseYear;
    boolean isAvailable;

    public static void main(String[] args) {
        Movie m = new Movie();

        m.title = "Inception";          // write
        m.releaseYear = 2010;
        m.isAvailable = true;

        System.out.println(m.title);        // read
        System.out.println(m.releaseYear);
        System.out.println(m.isAvailable);
    }
}
Inception
2010
true
  • reference.field = value writes a field.
  • reference.field reads it.

Each object owns its data

Every object gets its own copy of the fields:

Movie a = new Movie();
Movie b = new Movie();
a.title = "Inception";
b.title = "Dune";
System.out.println(a.title);   // Inception: b's change doesn't touch a

Two Movie objects are two independent blocks of memory. That's the point of objects: one class, as many instances as you need, each representing a different movie.

Initializing a field on its declaration

You can give a field its starting value right where you declare it:

public class Episode {
    int episodeNumber = 1;
    String platform = "Netflix";

    public Episode() {
        System.out.println("Episode " + episodeNumber + " on " + platform);
    }

    public static void main(String[] args) {
        new Episode();
    }
}
Episode 1 on Netflix

The order is guaranteed:

  1. Fields get their inline values, top to bottom.
  2. Then the constructor body runs.

So the constructor already sees 1 and "Netflix". It can also assign new values: the last write wins.

A field with no inline value keeps its default (null, 0, false) until something assigns it. The lab shows both cases side by side.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

โ† new and constructors ยท Next: the lab โ†’