What is Encapsulation?

Java encapsulation is one of the four fundamental object-oriented programming (OOP) principles, along with inheritance, polymorphism, and abstraction. Encapsulation serves as a fundamental concept in object-oriented programming, emphasizing the bundling of a class’s attributes (data) and methods (functions) into a cohesive unit. This item, referred to as a class, provides an organised method of interacting with the functionalities and underlying data. Encapsulation’s main goal is to prevent outside interference from accessing a class’s internal operations while enabling restricted access via clearly specified interfaces.

In Java, this protection is accomplished by employing access modifiers, which regulate the visibility of class members, encompassing fields and methods.

  1. public: Members with this modifier are accessible from any other class.
  2. protected: Members with this modifier are accessible within the same package and subclasses (even if they are in a different package).
  3. default (also known as package-private): Members with no explicit access modifier are accessible only within the same package.
  4. private: Members with this modifier are accessible only within the same class.

Making the class fields private and making the getter and setter methods (accessors and mutators) public to access and edit the fields is a recommended practice when applying encapsulation. By doing this, you may manage the data’s access and modification, making sure that it abides by certain guidelines or limitations specified in the class.

Get and Set:
Private variables are only accessible within the same class and cannot be accessed by external classes or objects.
On the other hand, if we make the get and set methods public, then it is feasible to access them.
he “get” function retrieves the variable’s value, while the “set” function assigns a new value.

The Java class you provided, named, demonstrates encapsulation with private fields and public getter and setter methods. Here’s a brief explanation of the class:

public class Person {
    private String name;
    private int age;

    // Getter method for 'name' field
    public String getName() {
        return name;

    // Setter method for 'name' field
    public void setName(String name) {
        this.name = name;

    // Getter method for 'age' field
    public int getAge() {
        return age;

    // Setter method for 'age' field
    public void setAge(int age) {
        this.age = age;
    1. Private Fields: The class person has two private fields: name and age. These fields are not directly accessible from outside the class, which is a crucial aspect of encapsulation. Other classes or code cannot directly modify or read these fields.
    2. Getter Methods: The class provides public getter methods to access the private fields. For the name field, the getter method getName() returns the value of the name For the age field, the getter method getAge() returns the value of the age field.
    3. Setter Methods: The class also provides public setter methods to modify the private fields. For the name field, the setter method setName(String name) takes a String parameter name and sets the value of the name field to the provided value. For the age field, the setter method setAge(int age) takes an int parameter age and sets the value of the age field to the provided value.

    By providing getter and setter methods, the class allows external code to access and modify the name and age fields indirectly, while still maintaining control over the data. If necessary, the class can add more logic to the getter and setter methods to impose restrictions or validation criteria.

    To guarantee that the supplied age is a positive number and is within a suitable range, for instance, the class can include logic in the setter method setAge(int age). Similarly, the setter method setName(String name) could check if the provided name is not empty or null.

    Overall, this is a simple example of encapsulation in Java, and it demonstrates how you can protect the internal data of a class and provide controlled access to it through well-defined interfaces (getter and setter methods).

    You must first construct an instance (object) of the Person class in order to use it and invoke its methods. Once the object is formed, you can access and alter the private fields (name and age) using its getter and setter methods. Here’s how you can do it:

public class Main {
    public static void main(String[] args) {
        // Create an instance of the Person class
        Person person = new Person();

        // Use the setter methods to set the name and age of the person
        person.setName("John Doe");

        // Use the getter methods to retrieve and display the name and age of the person
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());

In this example, we’ve created a Main class with a main method. Inside the main method, we create an object of the Person class named person.
We then use the setter methods (setName and setAge) to set the name to “John Doe” and the age to 30.
Finally, we use the getter methods (getName and getAge) to retrieve the name and age of the person object and print them to the console.

When you run the Main class, it will output:

Name: John Doe

Age: 30

This demonstrates how to call the methods of the Person class and access its encapsulated data through the getter and setter methods.

How does encapsulation work?

Encapsulation involves combining data attributes and their associated methods into a cohesive unit, commonly referred to as a class. The structure and behavior of objects that belong to a class are defined by the class, which acts as a blueprint or template. A class’s encapsulation acts as a barrier, keeping outside observers from seeing into its internal workings. It orchestrates access to the class’s inner workings through precisely defined interfaces, maintaining the integrity and security of its data and functionality.

Here’s how encapsulation works in Java:

  1. Access Modifiers: In Java, access modifiers are used to control the visibility of class members (fields and methods) from outside the class. The four access modifiers are publicprotecteddefault(package-private), and private.
    • public: Members with this modifier are accessible from any other class.
    • protected: Members with this modifier are accessible within the same package and subclasses (even if they are in a different package).
    • default(package-private): Members with no explicit access modifier are accessible only within the same package.
    • private: Members with this modifier are accessible only within the same class.
  2. Private Fields: Encapsulation primarily revolves around the practice of setting class fields (data members) to a private visibility level, ensuring data protection and control. By doing so, these fields are not directly accessible from outside the class, and their values can only be read or modified through methods provided by the class (getter and setter methods).
  3. Getter and Setter Methods: Public getter and setter methods, often referred to as accessors and mutators, serve the purpose of offering controlled access to private fields. They grant external code the ability to both retrieve and update the private field values, while also enabling the class to enforce validation rules or other operations as needed.
  4. Data Integrity and Validation: By encapsulating the data and providing controlled access through setter methods, the class can ensure that the data adheres to specific rules and constraints. For example, a class might enforce that a certain field can only accept positive integers or that a string field must not be empty.

Encapsulation is essential for maintaining the integrity of the class’s data and protecting it from accidental or unauthorized modifications. It also empowers the class to adapt and modify its internal workings without causing disruptions to the code that relies on the class’s public interface. Users of the class don’t need to know anything about the internal workings of the class; they just need to know how to interact with its public methods.

EWhen it comes to object-oriented programming, encapsulation is similar to the magic ingredient that makes your code stronger, clearer, and less prone to errors. It’s all about tucking away the inner workings of your objects to keep your code tidy and safe. This division of responsibilities protects your code from inadvertent hiccups and bugs while also making it easier to read. In a nutshell, encapsulation is your trusty tool for maintaining well-structured and hassle-free code.

More example:

// Employee is a class 

public class Employee {
        //HERE  id, name, ssn, a are 
        //Class Properties OR Class varible OR
        //Class Attribute OR class field
        int id;              //instance variable
        private String name; //instance variable
        private int ssn;     //instance variable  
        //Access Modifier
        int a;      //NOT an instance variable
        //Q: What is instance Variable?
        //Ans:The class variable which is used during instantiation.
        //Here Private(keyword) is called an Access Modifier
        //Q: What is Access Modifier?
        //Ans: Access Modifier Modify's the   
        //     Visibility and Accessibility of any Data
        //Access Modifier GRANT Visibility and Accessibility Privilege
        //Access Modifier REVOKE Visibility and Accessibility Privilege

        //For Private Access Modifier
        //Host Class - has Visibility and Accessibility ONLY
        //Other Class - NO Visibility and Accessibility
        Employee(int id, String name, int ssn) {
                this.id = id;
                this.name = name;
                this.ssn = ssn;
        //this method is called Setters 
        //- which set's any value to a Variable 
        void setSsn(int ssn) {
        //this method is called Getters
        //- which get's any value from a Variable 
        int getSsn() {
                return this.ssn;
        void setName(String name) {
                this.name = name;
        String getName() {    
                return this.name;

public class EmployeeDemo {

        public static void main(String[] args) {
                Employee karim;
                // instantiating karim
                karim = new Employee(1, "Karim", 11111111); 
                //replace SSN value
                //karim.ssn =2222222;
                //here we hide the name of SSN variable successfully 
                //This process is called Encapsulation
                //Q: What is Encapsulation?
                //Ans: Encapsulation is the process of Hiding any Class Member
                //     from Other Classes
                int r = karim.getSsn();
                System.out.println("Karim ssn: " + r );
                //karim.name = "Karim Ali";
                karim.setName("Karim Ali");
                System.out.println("Karim Name: " + karim.getName()  );
                //System.out.println("Karim ssn: " + karim.ssn );
                //Req: Hide ssn
                Employee maria;
                maria = new Employee(2, "Maria", 55555555);




Karim ssn: 22222222

Karim Name: Karim Ali

Explanation of this code: 

The code you’ve shared defines two Java classes: Employee and EmployeeDemo, which illustrate the concepts of instance variables, access modifiers, encapsulation, and getters and setters. Here’s a breakdown of the code:

  1. Employee Class:
    • The Employee class represents an employee and has three instance variables: id, name, and ssn. These variables are private, which means they can only be accessed within the class.
    • a is declared but not used as an instance variable because it lacks the “private” keyword.
    • An instance variable is a class variable that is specific to each instance of the class (each employee in this case).
  2. Instance Variables and Access Modifiers:
    • Instance variables are attributes associated with each instance of the class.
    • Access modifiers like private control the visibility and accessibility of class members. Private variables can only be accessed within the same class.
  3. Setters and Getters:
    • Setters (e.g., setSsn) are methods used to set the values of private instance variables.
    • Getters (e.g., getSsn) are methods used to retrieve the values of private instance variables.
  4. Encapsulation:
    • The code demonstrates encapsulation, which is the practice of hiding the implementation details (in this case, the ssn and name variables) and providing controlled access to the data through methods like setSsn and getSsn.
    • Encapsulation helps maintain data integrity and security by preventing unauthorized access to private variables.
  5. EmployeeDemo Class:
    • The EmployeeDemo class is used to demonstrate the Employee class.
    • It creates instances of the Employee class for employees named Karim and Maria.
    • It showcases how to set and get values for their attributes (ssn and name) using setters and getters.
    • It also hides the ssn value from direct access by using the encapsulation concept, ensuring that the ssn variable is not accessible outside the class.

In summary, the code provides a basic example of an Employee class with private instance variables, access modifiers, and encapsulation principles for data security. The EmployeeDemo class demonstrates how to create and interact with Employee objects while adhering to encapsulation practices to protect sensitive information like Social Security Numbers (ssn).


Access Modifiers with a table chart

    Four Types of Access Modifire:

  • Private
  • Public
  • Protected
  • Default

 The example below:

public class Calculator {
        public int a;
        protected int b;
        private int c;
        int d;
        public Calculator(int a, int b) {
        public int addition(int a, int b) {
                return a+b;
        private int findSFT(int width, int length) {
                return width*length;
        double calculateRent(int width, int length, double rate) {
                return this.findSFT(width, length) * rate;


public class MainCalculator {
        public static void main(String[] args) {
                Calculator myCal;
                myCal = new Calculator(5, 2);
                int result =myCal.addition(5, 2);
                System.out.println("Addition result: " + result);
                double rent = myCal.calculateRent(10, 20, 5.0);
                System.out.println("Rent is " + rent);



Addition result:7

Rent is 1000.0

Explanation of this code:

Calculator Class:

The Calculator class is designed to perform various mathematical operations, and it demonstrates different access modifiers (public, protected, and private) for class members, as well as method overloading and encapsulation.

  1. Instance Variables:
    • a, b, c, and d are instance variables of different access levels. a is public, b is protected, c is private, and d has package-private (default) access.
  2. Constructor:
    • The class has a constructor that takes two parameters, a and b, and initializes the instance variables with these values.
  3. Public Method addition:
    • The addition method takes two integers, a and b, and returns their sum.
    • This method is public, so it can be accessed from any class.
  4. Private Method findSFT:
    • The findSFT method is private, making it accessible only within the Calculator class.
    • It calculates the square footage of a rectangle by multiplying its width and length.
  5. Package-Private Method calculateRent:
    • The calculateRent method calculates the rent for a rectangular space, taking the width, length, and a rate as parameters.
    • It uses the private method findSFT to calculate the square footage and then multiplies it by the rate to determine the rent.
    • Since it has package-private access, it can be accessed only from classes within the same package.

MainCalculator Class:

The MainCalculator class contains the main method, which is the entry point for the Java program.

  1. Creating an Instance of Calculator:
    • In the main method, an instance of the Calculator class, myCal, is created by calling its constructor with the values 5 and 2.
  2. Using the addition Method:
    • The addition method of myCal is called with the arguments 5 and 2, and the result is stored in the result variable.
    • The result is then printed, displaying the addition operation’s outcome.
  3. Using the calculateRent Method:
    • The calculateRent method of myCal is invoked with the values 10, 20, and a rate of 5.0.
    • The calculated rent is stored in the rent variable, which is printed out to show the calculated rent.

In conclusion, this code illustrates object creation, encapsulation, and method overloading while offering a basic example of a Calculator class with multiple access modifiers for class members. The MainCalculator class showcases how to use the Calculator class to perform mathematical operations and calculate rent based on square footage and rate.


Visited 1 times, 1 visit(s) today

Comments are closed.