bhylu.com

Advertisements

Java Create an Object with State and Behaviour

A class describes a type of object. An instance gives that type its own state, so two bookings can follow the same rules without sharing the same reserved-seat count.

Understand the idea

A field holds state belonging to an instance unless it is declared static. An instance method can read or update that state. Creating an object with new calls a constructor; storing its reference in a second variable does not make another independent object. Start by modelling a small responsibility, such as a reservation, rather than building one class that contains every operation in an application.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    static class Reservation {
        int seats;
        String summary() { return seats + " reserved"; }
    }

    public static void main(String[] args) {
        Reservation first = new Reservation();
        Reservation second = new Reservation();
        first.seats = 3;
        second.seats = 5;
        System.out.println(first.summary());
        System.out.println(second.summary());
    }
}

Expected output

3 reserved
5 reserved

The two new expressions create separate Reservation instances. Each summary call uses the seats field of its receiver. The nested declaration keeps this first example in one source file; a larger project would usually place a domain class in its own file. Publicly writable fields are useful here to expose the mechanism, not a final design for protected booking rules.

Check the official Java documentation for detailed contracts and supported options.