Java classes that model real app data
Turn a note into a small, immutable data model with a clear public interface.
What you’ll learn
Before you start
- Java variables and methods
1. Model a note
public final class Note {
private final String title;
public Note(String title) {
if (title == null) throw new IllegalArgumentException("title is required");
this.title = title;
}
public String getTitle() { return title; }
}2. Construct an instance
Note note = new Note("Learn Android");
System.out.println(note.getTitle());Private state and a small public interface make an object easier to reason about. A final class prevents subclassing; a final field cannot be reassigned after initialization. This works well here because String is immutable too.
Expected output
The Java program prints Learn Android. Creating a note with null throws the explicit validation error.
Troubleshooting
Put the public class in Note.java. A constructor has no return type and must have the same name as its class.