Advertisement
Google Ad Slot: content-top
Java Encapsulation
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It is the process of wrapping data (fields) and methods (behavior) together into a single unit (class) and restricting direct access to them. Instead, access is provided through public methods, known as getters and setters.
In Java, encapsulation is implemented by:
- Declaring fields as private.
- Providing public getter and setter methods to access and update the values of the fields.
Example
class Human{
private int age; // private = restricted access
// Getter
public int getAge(){
return age;
}
// Setter
public void SetAge(int a){
age=a;
}
}
public class Main {
public static void main(String[] args){
Human obj=new Human();
obj.SetAge(30);
System.out.println("Name : "+obj.getAge());
}
}