Core Java
11 — Constructors & Encapsulation
Previous: 10 Classes & Objects · Next: 12 Inheritance & Polymorphism
▶️ java pkg1core/core26ConstructorsDemo.java · java pkg1core/core10Encapsulation.java
Constructors initialize objects
1class Employee {2 final String name;3 final int id;4 5 Employee(String name, int id) { // constructor6 this.name = name;7 this.id = id;8 }9}- Same name as class, no return type
- If you write no constructor, compiler adds a no-arg default
- Once you define any constructor, default is not generated
Constructor chaining
1Employee() {2 this("Unknown", 0); // must be first statement3}4 5Employee(String name, int id) {6 this(name, id, "General");7}8 9Employee(String name, int id, String dept) {10 this.name = name;11 this.id = id;12}this(...) calls another constructor in the same class.super(...) calls parent constructor (in subclasses).
Encapsulation — hide internal state
1class BankAccount {2 private double balance; // hidden3 4 public double getBalance() { return balance; }5 6 public void deposit(double amt) {7 if (amt <= 0) throw new IllegalArgumentException("amt > 0");8 balance += amt;9 }10}| Access | Who can access |
|---|---|
private |
Same class only |
| package-private | Same package |
protected |
Package + subclasses |
public |
Everyone |
💡 Benefit: Invariants are protected — callers can't set balance = -999.
Immutable objects
Make fields final, no setters, defensive copies for mutable components.
1record Point(int x, int y) {} // compiler-generated immutable classNext → 12 Inheritance & Polymorphism Related → 01 Core Java
Source named in this chapter
- core26ConstructorsDemopkg1core/core26ConstructorsDemo.java
- core10Encapsulationpkg1core/core10Encapsulation.java