← कोर्स पर वापस जाएँ: Java from scratch

Encapsulation, equals and records

वीडियो जल्द आ रहा है

In the previous lesson the fields of Dog and Account were accessible from anywhere: it was enough to write account.balance = -1000 to leave the object in an absurd state. Encapsulation solves that problem: fields are declared private, so they can only be touched from inside the class, and public methods are offered to control how the state is read and modified. That way the class protects its own rules (for example, a balance never negative) and you can change its internal implementation without breaking the code that uses it.

private, getters and setters

There are four access modifiers: public (visible from anywhere), private (only inside the class), protected (the class, its package and its subclasses) and the default access, with no keyword, which limits to the package. To read a private field you write a getter (getBalance) and to change it, if needed, a setter (setName) that validates the data. A field that must never change is declared final and assigned only in the constructor. Practical rule: do not create setters out of habit; provide only the operations that make sense for the business, such as deposit and withdraw instead of setBalance.

java
public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("ES01", 100);
        account.deposit(50);
        System.out.println(account.getBalance());   // 150.0
        System.out.println(account.withdraw(500));  // false: not enough money
        // account.balance = -1000;                 // error: balance has private access

        try {
            new BankAccount("", 10);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }

        Person p1 = new Person("Ana", 30);
        Person p2 = new Person("Ana", 30);
        System.out.println(p1 == p2);        // false: different objects
        System.out.println(p1.equals(p2));   // true: same content
        System.out.println(p1);              // Person[Ana, 30]
    }
}

class BankAccount {
    private final String id;          // never changes
    private double balance;

    BankAccount(String id, double initial) {
        if (id == null || id.isBlank()) {
            throw new IllegalArgumentException("id is required");
        }
        this.id = id;
        this.balance = Math.max(initial, 0);
    }

    double getBalance() { return balance; }

    void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        balance += amount;
    }

    boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }
}

class Person {
    private final String name;
    private final int age;

    Person(String name, int age) { this.name = name; this.age = age; }

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (!(other instanceof Person p)) return false;   // pattern matching (Java 16+)
        return age == p.age && name.equals(p.name);
    }

    @Override
    public int hashCode() { return java.util.Objects.hash(name, age); }

    @Override
    public String toString() { return "Person[" + name + ", " + age + "]"; }
}

records: immutable data without ceremony

The Person class above needed many lines for something very simple: storing two data items, comparing them and showing them. For that frequent case Java 16 introduced records. A record declares the components in one line and the compiler generates automatically the constructor, the accessors (name(), age()), equals, hashCode and toString. Its fields are final, so a record is immutable. You can add your own methods, static methods and a compact constructor to validate. A record cannot extend another class or declare additional instance fields; it is meant to be a plain data carrier, like a point, a currency, a name-value pair or a result row.

java
import java.util.HashSet;
import java.util.Set;

public class Main {
    record Point(int x, int y) {
        Point {                              // compact constructor: validation
            if (x < 0 || y < 0) throw new IllegalArgumentException("negative coordinate");
        }

        double distanceToOrigin() {
            return Math.sqrt(x * x + y * y);
        }

        static Point origin() {
            return new Point(0, 0);
        }
    }

    record Product(String name, double price) { }

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);                      // Point[x=3, y=4]
        System.out.println(p.x() + " " + p.y());    // 3 4
        System.out.println(p.distanceToOrigin());   // 5.0
        System.out.println(p.equals(new Point(3, 4)));  // true
        System.out.println(Point.origin());         // Point[x=0, y=0]

        Set<Product> set = new HashSet<>();
        set.add(new Product("Pen", 1.5));
        set.add(new Product("Pen", 1.5));           // equal: not added twice
        System.out.println(set.size());             // 1

        try {
            new Point(-1, 2);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

A note about equals and hashCode: they are always overridden together. If two objects are equal according to equals, they must return the same hashCode; otherwise collections such as HashSet or HashMap (which we will see in week 8) will behave wrongly and store duplicates. Notice also the pattern other instanceof Person p: it checks the type and declares the variable p in one step, with no manual cast. In a record the compiler does all this for you, which is why it is preferred for simple data.

जो सीखा उसे परखें

प्रश्न 1 / 1

What does a record generate automatically?

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →