new, references and constructors¶
โ Java 17 ยท Bringing Your Class to Life: Creating Objects ยท 1/3
From blueprint to object¶
This class describes every movie, but no movie exists yet. To create one, use new:
new Movie()reserves memory for oneMovieobject, in an area called the heap.- Its fields start with default values (
null,0,false). newreturns the object's address, stored inm.
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();
}
}
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.