Encaptulation

 

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 unit, known as a class, offers a structured approach to interact with the underlying data and functionalities. The primary objective of encapsulation is to shield the inner workings of a class from external interference while allowing controlled access through well-defined 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.

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 are only accessible within the same class and cannot be accessed by external classes or objects.
However, it is possible to access them if we provide public get and set methods.
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. 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 involves combining data attributes and their associated methods into a cohesive unit, commonly referred to 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 serves as a protective shield for a class, concealing its inner workings from the prying eyes of external entities. 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 simply need to understand how to engage with its public methods, without having to worry about the inner mechanisms governing how the class accomplishes its tasks.

Encapsulation is like the secret sauce in object-oriented programming that helps you whip up cleaner, sturdier, and less error-prone code. It’s all about keeping your code organized and secure by neatly tucking away the inner workings of your objects. This separation of concerns not only makes your code easier to understand but also shields it from unintended hiccups and glitches. 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.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: 

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) {
                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:

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 summary, this code provides a simple example of a Calculator class with various access modifiers for class members and demonstrates method overloading, encapsulation, and object creation. 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.

Close