Introduction
Encapsulation helps keep data safe and hidden inside an object. It stops other parts of the program from changing data in wrong ways.
Jump into concepts and practice - no test required
Encapsulation helps keep data safe and hidden inside an object. It stops other parts of the program from changing data in wrong ways.
public class ClassName { private DataType variableName; // hidden data public DataType getVariableName() { return variableName; // safe way to read data } public void setVariableName(DataType value) { variableName = value; // safe way to change data } }
Use private to hide data inside the class.
Use public getter and setter methods to control access.
name and allows safe access through methods.public class Person { private String name; public String getName() { return name; } public void setName(String newName) { name = newName; } }
public class BankAccount { private double balance; public double getBalance() { return balance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } public void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; } } }
This program shows how encapsulation protects the speed from being set to a negative value.
public class Car { private String model; private int speed; public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getSpeed() { return speed; } public void setSpeed(int speed) { if (speed >= 0) { this.speed = speed; } } public static void main(String[] args) { Car myCar = new Car(); myCar.setModel("Sedan"); myCar.setSpeed(50); System.out.println("Model: " + myCar.getModel()); System.out.println("Speed: " + myCar.getSpeed()); myCar.setSpeed(-10); // This will not change speed because of check System.out.println("Speed after invalid update: " + myCar.getSpeed()); } }
Encapsulation helps avoid bugs by controlling how data changes.
It makes your code easier to understand and maintain.
Always use getter and setter methods to access private data.
Encapsulation hides data to keep it safe.
It uses private variables and public methods.
This helps control and protect how data is used.
class Person {
private String name = "Alice";
public String getName() {
return name;
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.getName());
}
}public class Car {
public String model;
private int speed;
public void setSpeed(int speed) {
speed = speed;
}
}