Object-Oriented Programming (OOP) is based on four core concepts: abstraction, encapsulation, inheritance, and polymorphism.
In this article, we are going to discuss all about encapsulation in Java with examples.
Encapsulation is the mechanism of wrapping data (variables) and behavior (methods) together in a single unit (class).
The data of an encapsulated class will be hidden from other classes and cannot be accessed directly outside of it. It can only be accessed outside of the class through the public methods of its current class. Encapsulation helps achieve data hiding in Java.
An example of a fully encapsulated class is the Java Bean class.
To achieve encapsulation in Java:
Declare the variables of a class as private. Other classes cannot directly access private variables.
Provide public setter and getter methods. Using these public methods, private variables can be accessed or modified outside of the class.
The advantages of encapsulation in Java:
Encapsulation provides better control of class attributes and methods.
Encapsulation provides flexibility in Java programming. The programmer can change one part of the code without affecting other parts.
Encapsulation provides data security, which means we should declare private access modifiers with sensitive data (variables) and methods so that no one outside the class can directly access these private properties.
Class attributes can be made read-only if we use the get public methods or write-only if we use the set public methods.
Encapsulation provides easy debugging and testing, so it is good for unit testing.
Encapsulation allows the user to effectively use the existing code multiple times.
Here's a simple example of encapsulation in Java:
Class: AccountDetails.java
xxxxxxxxxx
Â
classAccountDetails {
privateStringcustomer_name;
privateintaccount_number;
privatefloatbalance;
privatevoiddocumentSubmitted() {
System.out.println("Submitted Documents : ");
System.out.println("Aadhar Card and PAN Card");
}
publicvoidgetSubmittedDocument() {
// Calling Private Method
documentSubmitted();
}
// Setter-Getter Methods =======
publicStringgetCustomer_name() {
returncustomer_name;
}
publicvoidsetCustomer_name(Stringcustomer_name) {
this.customer_name=customer_name;
}
publicintgetAccount_number() {
returnaccount_number;
}
publicvoidsetAccount_number(intaccount_number) {
this.account_number=account_number;
}
publicfloatgetBalance() {
returnbalance;
}
publicvoidsetBalance(floatbalance) {
this.balance=balance;
}
}
In this AccountDetails class, the attributes customer_name, account_number, and balance are encapsulated by making them private. Public getter and setter methods are provided to access and modify these attributes outside the class.
Class: EncapsulationExample.java
xxxxxxxxxx
Â
publicclassEncapsulationExample {
publicstaticvoidmain(String[] args) {
AccountDetailsaccountDtl=newAccountDetails();
// You cannot access private properties outside the class directly
// accountDtl.documentSubmitted();
// System.out.println(accountDtl.getBalance());
// Calling private method through public method outside the class
accountDtl.getSubmittedDocument();
// Setting Values in private variables using public setter methods
accountDtl.setCustomer_name("John");
accountDtl.setAccount_number(123456789);
accountDtl.setBalance(500000.0f);
// Access and printing private variables values using public getter methods
System.out.println("Customer Name : "+accountDtl.getCustomer_name());
System.out.println("Account Number : "+accountDtl.getAccount_number());
Submitted Documents : Aadhar Card and PAN Card Customer Name : John Account Number : 123456789 Account Balance : 500000.0
In the EncapsulationExample class, creating the object of the AccountDetails class, using the setter methods to set the values of the attributes of the AccountDetails class, and accessing the attributes using the getter methods.
By using encapsulation, we ensure that the internal representation of our class remains hidden from external manipulation, and we can control how data is accessed and modified, leading to more maintainable and robust code.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
Please share this article on social media to help others.
If you have any query or suggestion regarding this artical please share with us feedback@javabytechie.com
Encapsulation - Interview Questions and Answers
What is encapsulation in Java?
Encapsulation is the mechanism of wrapping data (variables) and behavior (methods) together in a single unit (class). The data of an encapsulated class will be hidden from other classes and cannot be accessed directly outside of it. It can only be accessed outside of the class through the public methods of its current class. Encapsulation helps achieve data hiding in Java.
How do we achieve 100% data encapsulation in Java?
Ans. In order to achieve 100% data encapsulation in Java, we need to follow the below points:
Declare all the class variables as private.
Define public setter and getter methods for accessing and modifying the private variables outside of the class.
Abstraction vs Encapsulation in Java
Ans. Abstraction and encapsulation are both core concepts of object-oriented programming. They are different from each other in terms of features and implementation in Java.
Abstraction is a mechanism for hiding implementation details from the user and displaying only functionality. whereas encapsulation is the mechanism of enclosing variables (data) and methods (behavior) in a single class.
Abstraction can be achieved using an abstract class or interface, whereas encapsulation requires declaring all the variables as private and providing public setter and getter methods.
In abstraction, problems are solved at the design level, whereas in encapsulation, they are solved at the implementation level.
Abstraction is the process of gaining information, whereas encapsulation is the process of containing the information.
Abstraction focuses on the object and not how it works, whereas encapsulation focuses on the object, its behavior and properties, and what it does.
Encapsulation and data hiding are both the same in Java?
Ans. No, data hiding means protecting the variables of a class from outside access, whereas encapsulation means wrapping or binding data into a single unit.
Data hiding focuses more on securing the data along with hiding it, whereas encapsulation focuses more on wrapping data to make classes and methods in the simplest form for the system.
Data hiding is both a technique and a process, whereas encapsulation is a sub-process of data hiding.
What is a "tightly encapsulated class" in Java?
A class is said to be tightly encapsulated if and only if all the data members (variables) of that class are declared private. If a class has all variables declared as private, and if it's inherited by another class that too has all private data members, then the later one is also said to be a tightly encapsulated class.
How to achieve data hiding in Java programming?
By declaring data members (variables) as private, we can achieve or implement data hiding in Java. Private properties of a class cannot be accessed directly outside of the class. The main advantage of hiding data is that we can achieve security.
Does reflection violate encapsulation in Java?
Reflection violates encapsulation because it reveals the internal data structures.
Explain a design pattern based on encapsulation in Java?
Ans. Encapsulation is a technique that Java uses in multiple design patterns, including the factory pattern, which generates objects.
For constructing the objects of those classes whose creation logic may vary, the factory design is a preferable option. Additionally, it is employed in the development of various interface implementations.
The JDK's BorderFactory class, which generates various border types and wraps the border generation code, is a nice illustration of encapsulation in Java.
What are the advantages of encapsulation in Java?
Please refer to the Tutorial Tab on the same page.
How do getter and setter methods help in encapsulation?
In encapsulation, all the private attributes are accessed or modified from the outside class using the getter and setter methods. All these getter and setter methods are declared public access modifiers.