Encaptulation

 

What is Encapsulation?

Java encapsulation is one of the four fundamental object-oriented programming (OOP) principles, along with inheritance, polymorphism, and abstraction. Encapsulation is the practice of bundling the data (attributes) and methods (behaviors) that operate on the data within a single unit, known as a class. The purpose of encapsulation is to hide the internal implementation details of a class from the outside world and provide controlled access to the class’s data and behaviors through well-defined interfaces.

In Java, encapsulation is achieved by using access modifiers to control the visibility of class members (fields and methods). There are four access modifiers in Java:

  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.

To apply encapsulation, it is a good practice to make the class fields private and provide public getter and setter methods (accessors and mutators) to access and modify the fields. By doing so, you can control how the data is accessed and modified, ensuring that it adheres to specific rules or constraints defined in the class.

Get and Set:
private variables can only be accessed within the same class (an outside class has no access to it)
However, it is possible to access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.

Here’s an example of encapsulation in a Java class:

The Java class you provided, named Person, 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. The class can implement additional logic inside the getter and setter methods to enforce constraints or validation rules, if necessary.

    For example, the class could add logic to the setter method setAge(int age) to ensure that the provided age is a positive value and within a reasonable range. 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).

    To use the Person class and call its methods, you’ll first need to create an instance (object) of the Person class. Once the object is created, you can use its getter and setter methods to access and modify the private fields (name and age). 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");
        person.setAge(30);

        // 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 works by bundling the data (attributes) and methods (behaviors) that operate on the data within a single unit, known as a class. The class serves as a blueprint or template that defines the structure and behavior of objects that belong to that class. Encapsulation ensures that the internal implementation details of the class are hidden from the outside world and that access to the class’s data and behaviors is controlled through well-defined interfaces.

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 typically involves making class fields (data members) private. 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 (also known as accessors and mutators) are used to provide controlled access to the private fields. These methods allow external code to read and modify the values of the private fields, but they also provide the class the opportunity to enforce any validation rules or business logic before accepting new values.
  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 enables the class to evolve and change its internal implementation without affecting the code that uses the class’s public interface. Clients of the class only need to know how to interact with its public methods, and they don’t need to be concerned about the internal details of how the class achieves its functionality.

By following the principles of encapsulation, you can create more robust and maintainable code in object-oriented programming. It promotes a clear separation of concerns and reduces potential bugs and unintended side effects in the codebase.

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.ssn=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;
                karim.setSsn(22222222);
                
                System.out.println(karim.a);
                
                //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);
                maria.setSsn(88888888);
                
                
        }//main


}//class

Output:

0

Karim ssn: 22222222

Karim Name: Karim Ali

Explanation of this code: 

This code represents a basic implementation of the Employee class along with a main method in the EmployeeDemo class to demonstrate its usage. Let’s break down the code step by step:

  1. The Employee class:
    • It defines four class members (also known as class attributes or class variables):
      • int id: An instance variable to store the employee’s ID.
      • private String name: An instance variable with a private access modifier, which means it can only be accessed within the Employee class itself and not from other classes directly.
      • private int ssn: An instance variable with a private access modifier, representing the employee’s Social Security Number. Like the name variable, this is also only accessible within the Employee class itself.
      • int a: Another instance variable, but without any access modifier specified. In Java, when no access modifier is provided, it defaults to package-private (visible within the same package). In this case, it is accessible within the same package as the Employee
    • The class also defines a constructor that takes three parameters (id, name, and ssn) to initialize the corresponding instance variables.
    • The class has three methods to interact with its private instance variables using the concept of getters and setters:
      • void setSsn(int ssn): A setter method that sets the value of the private ssn variable to the provided value.
      • int getSsn(): A getter method that retrieves the value of the private ssn variable and returns it.
      • void setName(String name): A setter method that sets the value of the private name variable to the provided name.
      • String getName(): A getter method that retrieves the value of the private name variable and returns it.

2. The EmployeeDemo class:

This class contains the main method, which serves as the entry point for the program.
3. Inside the main method of EmployeeDemo:

  • .An instance of the Employee class is created and assigned to the reference variable karim. The constructor is called to initialize its id, name, and ssn attributes with values 1, “Karim“, and 11111111, respectively.
    The setSsn method is used to update the value of the ssn attribute of the karim object to 22222222.
  • The getSsn method is called to retrieve the updated value of the ssn attribute, and it is stored in the variable r. Then, the value of r (the updated SSN) is printed.
  • The setName method is used to update the name attribute of the karim object to “Karim Ali“.
  • The getName method is called to retrieve the updated name attribute, and it is printed.
  • Another instance of the Employee class is created and assigned to the reference variable maria. The constructor is called to initialize its id, name, and ssn attributes with values 2, “Maria“, and 55555555, respectively.
  • The setSsn method is used to update the value of the ssn attribute of the maria object to 88888888.

The code showcases the concept of encapsulation, where the data (such as ssn and name) is hidden within the Employee class, and access to it is provided through public getter and setter methods. This ensures that the sensitive information, like the Social Security Number (ssn), is not directly accessible from outside the class, promoting better data security and code maintainability.

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) {
                this.a=a;
                this.b=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);
                
                
        }//main

}//class

Output:

Addition result:7

Rent is 1000.0

Explanation of this code:

The code consists of two classes: `Calculator` and `MainCalculator`.

1. The `Calculator` class:
– It defines four class members (class attributes or class variables):
– `public int a`: An instance variable with a public access modifier.
– `protected int b`: An instance variable with a protected access modifier.
– `private int c`: An instance variable with a private access modifier.
– `int d`: An instance variable without any access modifier specified. In Java, when no access modifier is provided, it defaults to package-private (visible within the same package). In this case, it is accessible within the same package as the `Calculator` class.

– The class also defines a constructor that takes two parameters (`a` and `b`) and initializes the corresponding instance variables with these values.

– The class has three methods:
– `public int addition(int a, int b)`: A public method that takes two integers as parameters and returns their sum.
– `private int findSFT(int width, int length)`: A private method that takes two integers (`width` and `length`) and returns their product (width * length).
– `double calculateRent(int width, int length, double rate)`: A method with default access modifier (package-private), which calculates the rent based on the `width`, `length`, and `rate` parameters by calling the private `findSFT` method and multiplying it by the rate.

2. The `MainCalculator` class:
– This class contains the `main` method, which serves as the entry point for the program.

3. Inside the `main` method of `MainCalculator`:
– An instance of the `Calculator` class is created and assigned to the reference variable `myCal` using the constructor. The constructor is called with the arguments `5` and `2`, which initialize the `a` and `b` attributes of the `myCal` object.

– The `addition` method is called on the `myCal` object, passing `5` and `2` as arguments, and the result (the sum of 5 and 2) is stored in the variable `result`. The result is then printed.

– The `calculateRent` method is called on the `myCal` object, passing `10`, `20`, and `5.0` as arguments. This method calculates the rent based on the dimensions (`width` and `length`) and the rate (`5.0`) and returns the result, which is stored in the variable `rent`. The value of `rent` is then printed.

The code demonstrates the use of different access modifiers (`public`, `protected`, and `private`) for class members, encapsulation of data (by making certain methods private), and how to create and use objects of a class.

Visited 1 times, 1 visit(s) today

Comments are closed.

Close