Object-Oriented Programming Lesson 17 of 21
Java Constructors and Encapsulation
Initialize objects with constructors, overload them, protect data with private fields, and control access with getters, setters and validation. Includes a BankAccount class.
In the last lesson, we set each field one by one after creating an object. That's tedious, and nothing stops someone from setting a price to −500. Constructors set up objects properly from the start, and encapsulation protects their data.
Constructors
A constructor is a special method that runs when you call new. It has the same name as the class and no return type:
class Student {
String name;
int gradeLevel;
Student(String name, int gradeLevel) {
this.name = name;
this.gradeLevel = gradeLevel;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Gabriela", 11);
System.out.println(s.name + ", Grade " + s.gradeLevel);
}
}
Output
Gabriela, Grade 11
One line now creates a complete, ready-to-use object.
Overloaded constructors
class Product {
String name;
double price;
int stock;
Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
Product(String name, double price) {
this(name, price, 0); // call the other constructor
}
}
public class Main {
public static void main(String[] args) {
Product a = new Product("Bigas", 52, 80);
Product b = new Product("Asukal", 70);
System.out.println(a.name + ": " + a.stock + " in stock");
System.out.println(b.name + ": " + b.stock + " in stock");
}
}
Output
Bigas: 80 in stock Asukal: 0 in stock
this(...) calls another constructor of the same class, avoiding duplicate code. If you don't write any constructor, Java provides an empty default one. Once you write your own, the default disappears.
Encapsulation: private fields
Encapsulation means hiding an object's data and allowing access only through methods that enforce the rules. Make fields private, then provide public getters (to read) and setters (to change, with checks):
class BankAccount {
private final String owner;
private double balance;
public BankAccount(String owner, double initialDeposit) {
this.owner = owner;
this.balance = Math.max(0, initialDeposit);
}
public String getOwner() { return owner; }
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount <= 0) {
System.out.println("Deposit must be positive.");
return;
}
balance += amount;
}
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) {
System.out.println("Withdrawal of ₱" + amount + " denied.");
return false;
}
balance -= amount;
return true;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acct = new BankAccount("Juan", 1000);
acct.deposit(500);
acct.withdraw(2000);
acct.withdraw(300);
acct.deposit(-50);
System.out.println(acct.getOwner() + "'s balance: ₱" + acct.getBalance());
// acct.balance = 1000000; // error: balance has private access
}
}
Output
Withdrawal of ₱2000.0 denied. Deposit must be positive. Juan's balance: ₱1200.0
Nobody outside the class can set balance directly. The only way to change it is through deposit and withdraw, which refuse invalid amounts. That's the whole point of encapsulation: the object protects itself.
Access modifiers
| Modifier | Who can access |
|---|---|
public | Everyone |
private | Only code inside the same class |
protected | Same package and subclasses |
| (none) | Same package only |
The usual rule: fields private, methods that others need public.
Getter and setter naming
- Getter:
getName(),getPrice(); for booleans,isActive(). - Setter:
setName(String name),setPrice(double price).
IDEs like NetBeans and IntelliJ can generate them for you (right-click → Generate / Insert Code).
Static fields: shared by all objects
class Ticket {
private static int nextNumber = 1; // shared counter
private final int number;
Ticket() {
number = nextNumber++;
}
int getNumber() { return number; }
}
public class Main {
public static void main(String[] args) {
Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
System.out.println(a.getNumber() + " " + b.getNumber() + " " + c.getNumber());
}
}
Output
1 2 3
A static field belongs to the class, not to each object, so all tickets share one counter. That's how queue numbers or receipt numbers can be generated.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04