Classes & Objects
Classes = Blueprints, Objects = Houses
Imagine you're an architect. You draw a blueprint for a house — it says "every house has a color, a number of rooms, and a door that can open and close." That blueprint is a class.
When you actually build a house from that blueprint, you get an object (also called an instance). You can build lots of houses from the same blueprint — one red, one blue, one with 3 rooms, one with 5. Each house is its own object, but they all follow the same structure.
Classes are the building blocks of every data structure you'll encounter, from linked lists to trees. A class bundles two things together:
- Fields (also called instance variables) — the data each object holds (color, name, score)
- Methods — the actions each object can do (run, jump, calculateTotal)
Your First Class
Access Modifiers & Encapsulation
Not everything inside a class should be accessible from the outside. Imagine a vending machine — you can press buttons and insert coins (public interface), but you can't reach inside and grab the mechanism (private internals).
Java has access modifiers to control this:
public— anyone can access it. It's the front door.private— only code inside the same class can access it. It's the locked vault.protected— accessible within the class and its subclasses.- (no modifier) — "package-private," accessible within the same package.
The practice of hiding internal data and exposing only what's necessary is called encapsulation. You use getters and setters to control access to private fields.