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);
}
}
reference.field = valuewrites a field.reference.fieldreads 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();
}
}
The order is guaranteed:
- Fields get their inline values, top to bottom.
- 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.