Classes and objects
Java objects combine state and behaviour behind a typed class.
What you will be able to do
- Keep fields private and expose intention-revealing methods.
- Validate constructor arguments immediately.
- Use records for small immutable value types.
In plain English
Fields hold state, methods define behaviour and constructors establish valid initial state. Prefer immutability when possible. Access modifiers are part of the design: expose only what callers need.
public record Course(String slug, String title, int lessons) {
public Course {
if (lessons < 1) throw new IllegalArgumentException("lessons");
}
}
public final class Progress {
private int completed;
public void markComplete() {
completed += 1;
}
public int completed() {
return completed;
}
}Your turn
EasyValidate a record
Write a record Lesson with title and minutes that rejects a negative minute value.
JAVA · starter
public record Lesson(String title, int minutes) {}Check your understanding before moving on.
Knowledge checkQuestion 1
Which access modifier hides a field from all other classes?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.