Advertisement

Google Ad Slot: content-top

Java Encapsulation

~1 min read · Java
On this page

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:

  1. Declaring fields as private.
  2. 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()); } }
Try it yourself