We may not have the course you’re looking for. If you enquire or give us a call on + 1-866 272 8822 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Encapsulation in Java is one of four core concepts available in Object Oriented Programming Languages. The four Object-Oriented Programming (OOP) concepts are Abstraction, Inheritance, Polymorphism and Encapsulation. These concepts make OOP languages like Java extremely popular among Developers. Java’s features, like platform independence, robustness and security, make it popular worldwide among Developers.
According to Statista, 33.27% of Developers worldwide use Java. Its popularity is thanks to its Object-Oriented concepts like Encapsulation, providing Developers various benefits. Read this blog to learn about Encapsulation in Java, its advantages, and the need for Encapsulation. Let’s dive in to learn more!
Table of Contents
1) Understanding what is Encapsulation in Java
2) Java programs using Encapsulation
a) Read and Write Program
b) Read-only Program
c) Write-only Program
3) Benefits of Encapsulation in Java
4) Conclusion
What is Encapsulation in Java?
Encapsulation refers to the powerful process of binding data, such as variables, classes and methods, together in a single entity. This singular entity (Class) is then used to call upon any necessary encapsulated data. A real-life example of this would be a capsule with several medicinal compounds present within it. When you see a capsule, you think of it as a cohesive unit, even though it has many smaller components. A similar example would be a matchbox; it has countless matchsticks and is considered a single unit.
The Encapsulation feature is commonly available in most OOP-based languages. Some such languages benefitting from Encapsulation are C++, C# and Java. However, Encapsulation isn’t limited to languages that use the OOP concept. Procedural Oriented languages like C can also use Encapsulation and benefit from it. However, this blog will focus on the uses of Encapsulation in Java.
Encapsulation is essentially the combination of Data Hiding and Abstraction concepts. Abstraction in Java refers to simplifying an entity by hiding its details, and Data Hiding refers to limiting access to data. Encapsulation achieves these feats with the help of specific keywords in Java, known as Access Modifiers.
Access Modifiers
Access Modifiers are used to limit the access of data within a class only to a certain degree. The level of access and privacy imposed on the class depends on the type of Access Modifier used in a program. Java has four kinds of Access Modifiers in it, which are as follows:
Public: Public class is the most commonly used Access Modifier in Java programming. Any data, method or class declared public can be accessed from anywhere, whether within the same or outside the class. It is accessible to both classes within the package it was declared in and outside the package. The keyword for the public Access Modifier is public, and it has the widest scope out of all Access Modifiers.
Protected: A protected class, declared with keyword protected, will only allow access within the package. Accessing it outside the package is still possible via child classes in Java, also called a derived class. A child class is any class which inherits the traits of another class. The child class will allow you to access the data and methods even while being a subclass of a different package.
Default: Default allows access to methods and data declared within the package, only limiting the access for members in other packages. The default Access Modifier is automatically allotted to a class in Java if no other Access Modifier is specified.
Private: A private class restricts access to methods and data declared in it within the respective class. This means members within other classes of the same Java program package can’t access it. These are generally used for nested classes and, thus, are not available in top classes. The keyword for a private class is private. Java program achieves Encapsulation by declaring the respective classes as private, limiting the access of a class, its data, and its members.
Uses of Encapsulation in Java
Encapsulation is one of the four core principles of OOPs and is used frequently in OOP-based languages. This allows Object Oriented Programming languages like Java to achieve what wouldn’t be possible in procedure-based languages like C. Some such feats of Encapsulation in Java programming are as follows:
Data Privacy: Using an Access Modifier in Java allows you to limit the access of data existing within a class. This keeps the inner workings of a class hidden from external entities. It also has the added benefit of abstraction, which removes any unnecessary details within the class.
Modularity: Encapsulation in Java allows you to use read and write-only classes based on your needs selectively. A Java program uses getter and setter methods to read and write data, creating a read-only or write-only class.
If you wish to create a read-only Java program, the general requirement is to avoid using the setter method. Some examples of setter methods will be setSalary(), setAllowance(), etc. Similarly, if you wish to create write-only classes, you must omit getter methods like getSalary(), getAllowance(), etc.
Reusable: Encapsulation allows you to reuse your previous data or Java codes in a new context. This is done with Inheritance, where new classes inherit properties of the encapsulated classes.
Efficient testing: Encapsulation allows for more efficient testing of an individual component within a software application. This form of testing is referred to as unit testing, and it involves checking small blocks of code, one at a time.
Try our Java Programming course to make use of benefits like Encapsulation!
Java programs using Encapsulation
Here are a few examples of Encapsulation in a Java program. Following the first example, you’ll start by declaring a public class Employee. As you declare three variables within the said class, “name”, “age”, and “salary”. You will use setter methods to allot values to those respective variables.
Read and Write Program
Java Program example 1: Here in this Java program, you’ll find the use of three setter methods declared, namely setName(), setAge() and setSalary() methods. This is due to the Access Modifier encapsulating the class, thus controlling how the data within it can be changed. To read those values and print out the output, we’ll use the getter method in the program. Here you should use the getName(), getAge() and getSalary() methods to get the output in a separate class EncapsulationDemo.
//Java program demonstrating Encapsulated data in Java
public class Employee
{
private String name;
private int age;
private double salary;
// Setter methods in Java to set the values of name, age, and salary public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public void setSalary(double salary)
{
this.salary = salary;
}
// Getter methods in Java to get the values of name, age, and salary
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getSalary()
{
return salary;
}
}
//Separate class declaration to test Encapsulation in Java
public class EncapsulationDemo
{
public static void main(String[] args)
{
// Create an object of the Employee class
Employee emp = new Employee();
// Set the values of the employee
emp.setName("Richard Wayne");
emp.setAge(20);
emp.setSalary(50000.0);
// Get the values of the employee and print them
System.out.println("Employee name: " + emp.getName());
System.out.println("Employee age: " + emp.getAge());
System.out.println("Employee salary: " + emp.getSalary())
; }
}
Output:
Employee name: Richard Wayne
Employee age: 20
Employee salary: 50000.0
Java Program example 2: Here is another program demonstrating Encapsulation in Java. In this Java program, a rectangle class has two instances, length and breadth. These variables are declared private; hence, they can only be accessed or modified by using getter and setter methods. In this case, you will find the use of getLength() and getWidth() getter methods, as well as setLength() and setWidth() setter methods, respectively.
The getArea() method in the Program uses the mathematical formula of an area of a rectangle. The Java program uses previously declared variables for length and width as respective values. Finally, we print out our statement using system.out.println statement in Java.
//Java program demonstrating Encapsulated data in Java
public class Rectangle
{
private double length;
private double width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
public double getLength()
{
return length;
}
public void setLength(double length)
{
this.length = length;
}
public double getWidth()
{
return width;
}
public void setWidth(double width)
{
this.width = width;
}
//Java getter method using Area of rectangle
public double getArea()
{
return length * width;
}
//Printing output of the Java program
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle(10, 5);
double area = rectangle.getArea();
System.out.println("Area of rectangle is: " + area);
}
}
Output: Area of rectangle is: 50.0
Become a Web Developer! Try our course, Web Development Using Java Training!
Read-only program
Java Program example 3: Let's see an example of a Read-only encapsulated program, also referred to as immutable objects. It is a programming technique where an object can’t be written or modified once created. In Java, this can be achieved by declaring the object's fields as private and only providing public methods to access those fields.
In this Program, you will need to declare a class, in this instance, a Car class. You'll need to declare some variables within that class; in this instance, they are make, model and year. You will need to use methods to display and print the values of these variables. Here the methods are getMake(), getModel(), and getYear() in the Program. As you will see, this Program does not use any setter method, making it possible to get outputs but not change them.
//Java program for read-only class
public class Car
{
private final String make;
private final String model;
private final int year;
public Car(String make, String model, int year)
{
this.make = make;
this.model = model;
this.year = year;
}
public String getMake()
{
return make;
}
public String getModel()
{
return model;
}
public int getYear()
{
return year;
}
}
//Different Java class declaration to test read-only class
public class Main
{
public static void main(String[] args)
{
Car car = new Car("Toyota", "Corolla", 2022);
System.out.println("Make: " + car.getMake());
System.out.println("Model: " + car.getModel());
System.out.println("Year: " + car.getYear());
}
}
Output:
Make: Toyota
Model: Corolla
Year: 2022
Write-only program
Java Program Example 4: Lastly, you will see an example of a write-only Encapsulation program. In this case, the class BankAccount has the variable balance declared within it. Later in the Main class, you’ll need to create an instance of the BankAccount class. Lastly, you’ll need to use methods to rewrite or initialise the variable’s value.
In this Java program, you’ll use setBalance() as a setter method to declare the value for the variable Balance. It is important to remember that while creating a read-and-write-only Program in Java is possible, they are rarely useful. These can be utilised in very particular instances; however, they rely on each other for greater efficiency.
Due to this Program being a write-only class, the changes will be made in the initial class, but no output will appear.
//Java program for write-only class
public class BankAccount
{
private double balance;
public void setBalance(double amount)
{
balance = amount;
}
}
//Different Java class declaration to test write-only class
public class Main
{
public static void main(String[] args)
{
BankAccount account = new BankAccount();
account.setBalance(1000.0);
}
}
Output: This program will have no output, being a write-only class.
Benefits of Encapsulation in Java
Encapsulation in Java, a crucial concept for effective real-time programming, offers several key benefits. Let's explore some of them:
1) Control over data: Classes gain complete control over data members and methods, often setting them as read-only. This control ensures data integrity and prevents unintended modifications.
2) Data hiding: Simplifies user interaction by hiding complex code implementations, thereby reducing the likelihood of errors and enhancing user experience.
3) Flexible data access: Enables setting class variables as read-only or write-only, tailored to specific requirements. This flexibility is crucial for protecting sensitive data while allowing necessary access.
4) Code reusability: Encapsulation facilitates the reuse of existing code, saving time and resources in developing new applications.
5) Ease of modification: It makes updating existing code more straightforward and less error-prone. This is essential for maintaining and scaling complex software systems.
6) Simplified testing: Unit testing becomes more straightforward with encapsulated code. This will lead to more reliable and maintainable software.
7) IDE support: Common IDEs support getters and setters, accelerating the coding process and improving Developer productivity.
Try our Java Programming Course to make use of benefits like Encapsulation!
Conclusion
Encapsulation is a method that allows you to bind data and methods into a single class. These classes can have varying degrees of access in Java, with more efficient testing and reusable codes. These degrees of privacy are decided via Access Modifiers. This blog discussed getter and setter methods used to work with Java Encapsulations. Hopefully, this blog will allow you to understand Encapsulation in Java, as well as its necessities, better than before. Thank you for reading.
Register for our Java Programming And Software Engineering Fundamentals Training course today!
Frequently Asked Questions
Encapsulation is referred to as data hiding because it restricts direct access to a class's data members, instead using methods like getters and setters. This approach hides the internal state of an object from the outside, ensuring controlled access and modification.
Abstraction in Java is about hiding the complexity of implementation by using abstract classes and interfaces, focusing only on what an object does. Encapsulation, on the other hand, is about hiding the internal state of an object and requiring all interaction to be performed through an object's methods.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various Java Courses, including Java Programming Course, JavaScript for Beginners and Java Engineer Training. These courses cater to different skill levels, providing comprehensive insights into Latest Java Technologies Trends.
Our Java blogs cover a range of topics related to Java, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Java Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
Upcoming Programming & DevOps Resources Batches & Dates
Date
Mon 13th Jan 2025
Mon 10th Mar 2025
Mon 19th May 2025
Mon 21st Jul 2025
Mon 15th Sep 2025
Mon 17th Nov 2025
Mon 15th Dec 2025