GCGrowCarrer

Constructors and Encapsulation

Locked

Lesson 10 of 60 · OOP · Medium

Finish these first:Classes and Objects →Or pass the tests below to unlock it now.

1

The big idea

Constructors initialize objects. Keep fields private and expose behaviour via methods; validate invariants in one place.

Think of it like this: Think of a Class as a cookie cutter (the blueprint) and each Object as an individual cookie stamped from it — each cookie can have its own frosting (state) while sharing the same shape (methods).
Key words (tap to learn):
2

Read the lesson

Constructors initialize objects. Keep fields private and expose behaviour via methods; validate invariants in one place.

class Account {
    private final String owner;
    private long cents;
    Account(String owner) { this.owner = Objects.requireNonNull(owner); }
}
3

Quick check

Before writing code: What should `new Solution.Account(5).balance()` return when your implementation of Constructors and Encapsulation is working?

4

Your challenge

2 sample tests, 1 hidden

Implement Account(long cents) that rejects negative values with IllegalArgumentException, and balance().

Stuck? Get a hint (free)
More learning tools(compare languages, visual guide, related lessons)

Compare with another language

See how Java compares side-by-side with Python.

Visual walkthrough

A diagram, a step-by-step animation, and short captions for Constructors and Encapsulation.

Mastery0%