Java has a strong mechanism for storing a class's data members and methods together called encapsulation. It is set up as a secure field that can only be accessed by class members.
The technique by which data (variables) and the code that operates on it (methods) are combined as a single entity in Java is known as encapsulation. The variables of a class are protected by an encapsulation so that only the methods of that class can access them.
Data wrapping is the definition of encapsulation. It is the system that links the code to the data it works with. Encapsulation can also be thought of as a barrier that stops code from outside the barrier from accessing the data.
In practise, encapsulation means that a class's variables or data are kept secret from other classes and are only accessible through member functions of the custom class in which they are specified.
By making the class's members or methods private, data hiding, like encapsulation, protects a class's data from view by other classes, but yet leaving the class open to the public or the end user without disclosing any specifics. It is also referred to as a combination of data concealing and abstraction behind the implementation using the abstraction idea.
Encapsulation can be accomplished by writing public methods in the class to set and get the values of the variables and by defining all variables in the class as private.
More is defined using the setter and getter method.
We have seen that encapsulation provides the pooling of data and related things with the motive of hiding the data and providing methods for seamless communication. Now let's look at an example:
Think of a car (any model will work). Now think about the components of the car. We can think of tires, steering wheels, engines, shafts, etc. These are nothing more than Car data members (if Car is a class, then they are variables). Now you might think of methods. It's simple, the methods of this car move. Driving, honking, etc. To summarize the example, a Car represents a class; components are data variables, and car auctions are methods.
Here we could see encapsulation. The various components (variables) are bound together in a Car (class) along with the many functions that these components (methods) use. We can also see that this encapsulation helps in abstraction. For example, you can't see the engine, shafts, or whole drive mechanism, but you can drive the car comfortably through some interfaces. This is the main feature of abstraction. The client does not care about the internal mechanism or representation of the data but only about completing the task using an interface (often provided by methods).
• Flexibility: It is more flexible and easier to change the encapsulated code according to the new set of requirements. For example, if the request to add/remove an employee project changes, we can simply update the logic in the setter() method or provided methods.
• Reusability: Encapsulated code can be reused across an application or across multiple applications.
• Maintainability: When application code is encapsulated into separate units (classes, interfaces, methods, getters/setters, etc.), it is easy to change or update a part of the application without affecting other parts, reducing developer effort and time.
• Testability: For an encapsulated class, writing tests is easier because the member variables are not scattered all around, which also reduces the time and effort of the tester.
• Data Hiding: The caller of the method will have no idea about the internal logic of the class because the member variables are not visible to the calling function. The caller only knows the parameters to be passed to the setter method (or any method) to initialize with that value.
The CoffeeMachine class sample was constructed using encapsulation. The brewing unit, beans, grinder, and configMap attributes each store the CoffeeMachine object's current state. These activities are carried out using the methods brewCoffee, brewEspresso, brewFilterCoffee, and addBeans.
The CoffeeMachine example project's other classes, including this one, can be copied at https://github.com/thjanssen/Stackify-OopAbstraction.
“`
import java.util.HashMap;
import java.util.Map;
public class CoffeeMachine {
private Map configMap;
private Map beans;
private Grinder grinder;
private BrewingUnit brewingUnit;
public CoffeeMachine(Map beans) {
this.beans = beans;
this.grinder = new Grinder();
this.brewingUnit = new BrewingUnit();
this.configMap = new HashMap();
this.configMap.put(CoffeeSelection.ESPRESSO, new Configuration(8, 28));
this.configMap.put(CoffeeSelection.FILTER_COFFEE, new Configuration(30, 480));
}
public Coffee brewCoffee(CoffeeSelection selection) throws CoffeeException {
switch (selection) {
case FILTER_COFFEE:
return brewFilterCoffee();
case ESPRESSO:
return brewEspresso();
default:
throw new CoffeeException("CoffeeSelection [" + selection + "] not supported!");
}
}
private Coffee brewEspresso() {
Configuration config = configMap.get(CoffeeSelection.ESPRESSO);
// grind the coffee beans
GroundCoffee groundCoffee = this.grinder.grind(
this.beans.get(CoffeeSelection.ESPRESSO), config.getQuantityCoffee());
// brew an espresso
return this.brewingUnit.brew(CoffeeSelection.ESPRESSO,
groundCoffee, config.getQuantityWater());
}
private Coffee brewFilterCoffee() {
Configuration config = configMap.get(CoffeeSelection.FILTER_COFFEE);
// grind the coffee beans
GroundCoffee groundCoffee = this.grinder.grind(
this.beans.get(CoffeeSelection.FILTER_COFFEE), config.getQuantityCoffee());
// brew a filter coffee
return this.brewingUnit.brew(CoffeeSelection.FILTER_COFFEE,
groundCoffee, config.getQuantityWater());
}
public void addBeans(CoffeeSelection sel, CoffeeBean newBeans) throws CoffeeException {
CoffeeBean existingBeans = this.beans.get(sel);
if (existingBeans != null) {
if (existingBeans.getName().equals(newBeans.getName())) {
existingBeans.setQuantity(existingBeans.getQuantity() + newBeans.getQuantity());
} else {
throw new CoffeeException("Each CoffeeSelection can only support one type of bean.");
}
} else {
this.beans.put(sel, newBeans);
}
}
}
“`
Java's encapsulation implementation has shown to be quite effective and helpful for real-time programming. The following are encapsulation's key advantages:
• A class has complete control over the data members and data methods.Only one kind of beans supported for each CoffeeSelection.
• The class will maintain read-only access to its data members and methods.
• Data hiding prevents the user from complex implementations in the code.
• Class variables can be read-only or write-only according to the programmer's requirements.
• Encapsulation in Java provides code reusability.
• Using encapsulation will help make changes to existing code quickly.
• Unit testing code designed with encapsulation is elementary.
• Standard IDEs support getters and setters; this makes coding even faster.
As a principle of object-oriented programming, Java encapsulation describes the grouping of data and the methods that interact with that data into a single entity.
It is often used as a means of hiding sensitive data. This approach restricts external access to specific attributes while allowing members of the current class to access them through public getter and setter methods. You can use these methods to determine which attributes can be read or updated and use them to validate the new value before changing the attribute.
About The Author:
Digital Marketing Course
₹ 29,499/-Included 18% GST
Buy Course₹ 41,299/-Included 18% GST
Buy Course