(Data Hiding + Controlled access)
private variables.
public getter and setter methods.
What is Encapsulation?
- Encapsulation is wrapping data and methods into a single class and restricting direct access using private variables.
why:
- It provides security, data control and better code organisation.
when:
- It is used when data needs protection and controlled access in large applications.
examples:
class Student {
private int age; // private variable (hidden)
private String name;
// Getter
public int getAge() {
return age;
}
// Setter
public void setAge(int age) {
if(age > 0) {
this.age = age;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setAge(22);
s.setName("Vishnu");
System.out.println(s.getName());
System.out.println(s.getAge());
}
}
real-time example;
class BankAccount {
private double balance;
public void deposit(double amount) {
if(amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
}
}
public void withdraw(double amount) {
if(amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(5000);
acc.withdraw(2000);
System.out.println("Balance: " + acc.getBalance());
}
}
encapsulation with validation:
class Employee {
private double salary;
public void setSalary(double salary) {
if(salary >= 10000) {
this.salary = salary;
} else {
System.out.println("Salary too low!");
}
}
public double getSalary() {
return salary;
}
}
Top comments (0)