Skip to content

new, references and constructors

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

From blueprint to object

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

This class describes every movie, but no movie exists yet. To create one, use new:

Movie m = new Movie();
  1. new Movie() reserves memory for one Movie object, in an area called the heap.
  2. Its fields start with default values (null, 0, false).
  3. new returns the object's address, stored in m.

m is a reference: it holds where the object lives, like a house address. m is not the object itself. This difference between references and objects comes back everywhere in Java.

The constructor

Right after reserving memory, new runs the class's constructor: code that prepares the new object.

public class Movie {
    String title;

    public Movie() {                          // constructor
        System.out.println("A Movie was created!");
    }

    public static void main(String[] args) {
        Movie m = new Movie();
    }
}
A Movie was created!

Three rules:

Rule Detail
Same name as the class Movie() in class Movie
No return type not even void โ€” that's what makes it a constructor
Called by new you never call it directly

A "constructor" with a return type, like public void Movie() { }, is just an ordinary method that happens to share the class name. new never runs it.

The default constructor

A class with no constructor at all still works with new:

public class Series {
    String name;
    int totalEpisodes;
}

// elsewhere
Series s = new Series();   // โœ… compiles

The compiler silently adds a default constructor: no parameters, empty body.

But as soon as you write any constructor yourself, the compiler stops adding it:

public class Series {
    String name;

    public Series(String name) {
        this.name = name;
    }
}

// elsewhere
Series s = new Series();   // โŒ compiler error: no constructor Series()

To support both new Series() and new Series("Dark"), write both constructors.

Now that objects exist, let's put data into them.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

Next: reading, writing and initializing fields โ†’