Object-oriented Java organizes data and operations into types. A class defines a common structure; an object is a particular instance of that structure. Consider a monitoring application that models server devices: each needs an identifier and its own load value, while every device follows the same validation rules. A class lets programmers enforce those rules without repeating validation throughout an application.
The lesson builds on OSJava.007 on methods and parameters. Review arrays and references, String immutability and equality, and control flow. The examples use synthetic readings, not operational thresholds.
Prerequisites and learning objectives
A local JDK 11 or newer, terminal access, and familiarity with variables, conditional statements and methods. The laboratory was compiled and run with OpenJDK 21.0.12.1.
- Distinguish classes, objects, fields, methods and references.
- Construct objects using new, overloaded constructors and constructor delegation.
- Explain instance state, shared aliases and static members.
- Enforce a state invariant through private fields and validated methods.
- Compile and test an isolated Java program, including rejected inputs, and explain its security boundaries.
1. Class architecture and instance state
A class declaration establishes a named reference type and its members. Fields represent state; methods operate on state or perform related tasks. An instance field belongs to an individual object, while a static field belongs to the loaded class rather than each object. A static method does not receive an implicit current-object reference. An instance method can access its receiver’s fields.
In Device a = new Device("A", 30);, Device is the declared reference type, a is a variable, new creates an instance and the constructor initializes it. Two successful calls to new create distinct instances. Assignment Device alias = a; copies a reference, not the object. Mutations through either reference affect the same instance. An uninitialized local reference cannot be read; a reference containing null points to no object and dereferencing it normally raises NullPointerException.
Bro Code, Java object-oriented programming, December 5, 2024. Supplementary introduction to classes and objects.
2. Constructors and initialization
A constructor has the class name and no declared return type. The compiler selects among overloads according to argument types and arity. If no constructor is explicitly declared, Java supplies a default no-argument constructor, subject to superclass initialization requirements. Declaring a parameterized constructor does not preserve an automatically supplied no-argument constructor.
The sample offers a one-argument constructor that delegates to the two-argument form with an initial load of zero. In Java 21, the explicit constructor invocation this(id, 0) must be the first constructor statement. The expression this.id identifies the receiver’s field rather than the parameter of the same name. A final instance field can be assigned during initialization and cannot subsequently be reassigned. A final reference alone does not make a referenced mutable object immutable.
Bro Code, Java constructors, December 5, 2024. Separate tutorial on initializing instances.
3. Encapsulation and invariants
An invariant is a condition valid objects must preserve. The demonstration requires a nonblank identifier and a load from 0 through 100 inclusive. Both fields are private, so ordinary unrelated client classes cannot directly assign them. Read methods expose the values; setLoad checks proposed values before changing the field. A rejected assignment throws IllegalArgumentException and leaves the previous value intact. The class is final to prevent subclassing.
Member access modifiers include public, protected, package-private (no modifier), and private. The laboratory uses a nested class, so the enclosing class and nested class have special private-member access permitted by Java; ordinary unrelated callers do not. Encapsulation reduces accidental misuse but does not provide encryption, authentication, authorization, or thread safety. A real multi-threaded monitoring service would need synchronization or another explicit concurrency design. Input validation is also required at external trust boundaries.
4. Reproducible laboratory
Save the following source as DeviceLab.java in a new local practice directory. The program uses no network, production data, external libraries, administrator privileges or filesystem changes beyond local compilation.
public class DeviceLab {
static final class Device {
private final String id;
private int load;
Device(String id) { this(id, 0); }
Device(String id, int load) {
if (id == null || id.isBlank()) {
throw new IllegalArgumentException("id required");
}
this.id = id;
setLoad(load);
}
String getId() { return id; }
int getLoad() { return load; }
void setLoad(int value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("load: 0..100");
}
load = value;
}
}
static void check(boolean ok) {
if (!ok) throw new AssertionError("check failed");
}
public static void main(String[] args) {
Device a = new Device("A", 30);
Device b = new Device("B");
check(a.getId().equals("A"));
check(a.getLoad() == 30);
check(b.getLoad() == 0);
check(a != b);
Device alias = a;
alias.setLoad(70);
check(a.getLoad() == 70);
check(b.getLoad() == 0);
try { a.setLoad(101); throw new AssertionError(); }
catch (IllegalArgumentException expected) { check(a.getLoad() == 70); }
try { new Device("", 0); throw new AssertionError(); }
catch (IllegalArgumentException expected) { check(true); }
a.setLoad(100);
check(a.getLoad() == 100);
System.out.println("9 checks passed; A=100, B=0");
}
}
From the practice directory, run:
javac -Xlint:all DeviceLab.java
java DeviceLab
Observed output from OpenJDK 21.0.12.1:
9 checks passed; A=100, B=0
The tests establish independent objects, constructor defaults, aliasing, boundary acceptance, rejection of invalid input and preservation of the old state. The explicit check method throws AssertionError when a condition fails; unlike Java’s assert keyword, it does not require the -ea runtime flag. The test suite is illustrative, not a comprehensive security or production-readiness assessment.
5. Safe workflow and security boundaries
- Use a local sandbox and synthetic device values; verify the installed JDK with javac -version.
- Compile with warnings enabled and stop on compile errors. Read the reported exception and confirm its origin.
- Test lower and upper limits, invalid identifiers, rejected loads and reference aliasing before changing the class.
- For production use, obtain authorization and change approval, review input and concurrency boundaries, test in staging, and define rollback. Never use synthetic 0–100 values as approved facility operating limits.
6. Practice exercises and knowledge check
- Create two devices with initial loads of 10 and 20. Change only the first to 40. Predict both values.
- Create an alias of the second device and set its load to 55. Does the original reference observe the change?
- Attempt a load of -1 and catch IllegalArgumentException. Verify the previous load remains intact.
- Why does a class with an explicit Device(String id) constructor not automatically accept new Device()?
- Explain why a private field does not prevent two threads from racing over its value.
- Write an additional test for a null identifier and another for a valid load of zero. Use synthetic inputs only.
7. Answer key
- The first load becomes 40; the second stays 20 because they are separate objects.
- Yes. Both variables hold references to the same object, whose load becomes 55.
- The exception is thrown before assignment; the previous value remains unchanged.
- An explicit constructor suppresses the compiler-provided default constructor. A zero-argument overload must be declared if required.
- Access control restricts which code can access the member; it does not make a sequence of reads and writes atomic or coordinate concurrent callers.
- Construct new Device(null, 0) inside a try/catch and expect IllegalArgumentException. For zero, construct a valid device with load 0 and check getLoad() == 0.
Glossary
Class: declared type and member definitions. Instance: individual object. Field: member variable. Constructor: initialization declaration. Reference: value identifying an object or null. Alias: another reference to the same object. Encapsulation: controlled access to representation and behavior. Invariant: condition preserved across valid operations.
Primary references
Official Java documentation: Creating Classes; Providing Constructors; Creating and Using Objects; More on Classes and access control.

Leave a Reply