Skip to content

Lab: two independent streaming objects

☕ Java 17 · Bringing Your Class to Life: Creating Objects · 3/3

Goal: create two objects from the same class and prove they keep their own data, including inline defaults nobody changed.

Setup: create StreamingContent.java and NetflixDemo.java in the same folder.

Step 1 — The class and its fields

StreamingContent.java:

public class StreamingContent {
    String title;
    int releaseYear = 2024;
    boolean isAvailable = true;
}

title has no sensible default, so it stays null until someone sets it. A new title is assumed to be from 2024 and available.

Step 2 — A constructor

Inside the class:

    public StreamingContent() {
        System.out.println("Content ready: " + title);
    }

It runs automatically on every new.

Step 3 — Create two objects

NetflixDemo.java:

public class NetflixDemo {
    public static void main(String[] args) {
        StreamingContent movie1 = new StreamingContent();
        movie1.title = "Squid Game";
        movie1.releaseYear = 2021;

        StreamingContent movie2 = new StreamingContent();
        movie2.title = "Money Heist";
    }
}

movie1 overrides the year. movie2 deliberately leaves it alone.

Step 4 — Print and run

At the end of main:

        System.out.println(movie1.title);
        System.out.println(movie2.title);
        System.out.println(movie2.releaseYear);
$ javac StreamingContent.java NetflixDemo.java
$ java NetflixDemo
Content ready: null
Content ready: null
Squid Game
Money Heist
2024
  • Content ready: null, twice: the constructor ran once per new, before any title was set.
  • Squid Game, Money Heist: each object has its own title.
  • 2024: movie2 kept the inline default. Changing movie1's year didn't affect it.

Final code

// StreamingContent.java
public class StreamingContent {
    String title;
    int releaseYear = 2024;
    boolean isAvailable = true;

    public StreamingContent() {
        System.out.println("Content ready: " + title);
    }
}
// NetflixDemo.java
public class NetflixDemo {
    public static void main(String[] args) {
        StreamingContent movie1 = new StreamingContent();
        movie1.title = "Squid Game";
        movie1.releaseYear = 2021;

        StreamingContent movie2 = new StreamingContent();
        movie2.title = "Money Heist";

        System.out.println(movie1.title);
        System.out.println(movie2.title);
        System.out.println(movie2.releaseYear);
    }
}

Setting fields one by one after new gets repetitive. Passing values to the constructor directly comes later in the course.

Full code on GitHub

← Object data · Back to the series


🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)