Here is the thing about fields in a class โ if you make them public, anyone can
change them to whatever they want. That might sound fine until someone sets the
age of a person to -5.
Encapsulation is the idea of keeping the internal data of an object private and only allowing controlled access through methods. It is one of the core principles of object-oriented programming.
Private Fields
The private keyword means the field can only be accessed from within the
same class. No other class can touch it directly.
public class Person {
private String name;
private int age;
}
If you try to do person.name = "John" from another class, Java will
refuse to compile it. That field is locked down.
Getters and Setters
If the fields are private, how do you read or change them? You write getter and setter methods. These are public methods that control access to the private fields.
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Amina");
p.setAge(25);
System.out.println(p.getName() + " is " + p.getAge());
}
}
Look at setAge(). It checks that the age is positive before setting it.
That is the whole point of encapsulation โ you can add validation, logging, or any
logic you want before allowing changes to the data.
Access Modifiers
Java gives you a few options for controlling access to your classes, fields, and methods:
privateโ only accessible within the same classdefault(no keyword) โ accessible within the same packageprotectedโ accessible within the same package and by subclassespublicโ accessible from anywhere
public class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
The balance is private. Nobody can just reach in and change it. They
have to go through the deposit() method, which makes sure they are
depositing a positive amount. That is data hiding in action.