Classes, Objects and Encapsulation
A class is a blueprint. An object is a real thing made from it with new. A constructor sets up a new object.
Encapsulation means keeping fields private and giving controlled access through public methods. Nobody can set a wrong price from outside.
Java is an object-oriented language: programs are built from objects that hold data (fields) and behaviour (methods). A Product class describes what every product has and can do; new Product("Pen", 20) creates one real product in memory. You can create thousands of objects from one class.
Why encapsulation? Imagine anyone in a big team could set product.price = -500 directly. Bugs like that are hard to find. By making the field private and offering a setPrice method that checks the value, the class protects its own data. Other code uses the public methods and doesn't need to know how the class works inside.
Getters (getPrice()) read a value; setters (setPrice()) change it with checks. The keyword this means "this object" and is used to tell a field apart from a parameter with the same name.
Immutable classes
An immutable object can never change after it is made (like String). To make one: mark the class final, make fields private final, and give no setters.
Immutable objects are simpler and safer: once created, nobody can change them, so they can be shared freely between different parts of a program (even between threads running at the same time) without surprises. Money amounts, dates and ids are good candidates.
public final class Money {
private final double amount;
public Money(double amount) { this.amount = amount; }
public double getAmount() { return amount; }
}- A class is a blueprint;
newcreates objects from it. - Constructors set up new objects;
thismeans the current object. - Encapsulation: private fields, public methods that check values.
- Immutable classes can't change after creation - safer to share.
