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 organized 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.
- 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 (also known as 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.
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:
-
- 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.
- 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.
- 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:
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:
- 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 public, protected, default(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.
- 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).
- 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.
- 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.
When 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.
Access Modifiers with a table chart
Four Types of Access Modifire:
- Private
- Public
- Protected
- Default
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.
- 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.
- Constructor:
- The class has a constructor that takes two parameters, a and b, and initializes the instance variables with these values.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.