What is Encapsulation in Java with Realtime Example - onlyxcodes

Thursday 12 May 2022

What is Encapsulation in Java with Realtime Example

In this post, you will learn about the Java concept of encapsulation. It is one of the key principles of OOP.


Encapsulation is one of the most important concepts in object-oriented programming because it provides security by protecting the class's sensitive data from the users.


It is the process of covering information specifics while protecting the object's data and behavior. It's simple to test the encapsulating class.


This article also covers the following elements, as well as encapsulation.


What is Encapsulation?


How to Implement Encapsulation in Java


Advantages of Encapsulation. 


Why do we need encapsulation?


Data Hiding. 


How to achieve Data Hiding in Java?


Difference Between Abstraction and Encapsulation In Java


encapsulation in java


What is Encapsulation in Java?

In Java, encapsulation is a strategy for wrapping data (variables) and code operating on methods into a single entity.


Encapsulation, in other terms, is a programming technique that binds class members (variables and methods) together and stops other classes from accessing them.


We can protect variables and methods from outside manipulation and unauthorized access this way.


The class is the ideal illustration of encapsulation since it binds its variables and methods together while hiding their complexity from other classes.


A car engine is another example of encapsulation. Basically, it's an encapsulation of multiple different parts.


An engine, for example, appropriately binds pieces like breaking, gear system, batteries, and others that are not visible to the driver.


The engine will behave as a class if combinations of pieces include variables and methods, and the entire process is known as encapsulation, as illustrated in the diagram below.


data hiding - difference between abstraction and encapsulation in java - advantages of encapsulation in java - oops


We declare variables as private in the class to block other classes from accessing them directly in the encapsulation methodology.


The public Java getter and setter methods can be used to retrieve the required encapsulated data.


If a variable is made private in a class, it cannot be accessible by anyone outside the class, thus hiding the variable. As a result, it's also known as data hiding.


How to Implement Encapsulation in Java

In a Java application, there are two essential points where we can use encapsulation.


1. Declaring a class's instance variable as private. so that no one outside the class may access it directly.


2. To change and retrieve the values of variables, provide public setter and getter methods in a class.


In the example below, we build encapsulation in Java.


package MyPackage;

class Employee
{
	private int empid;
	private String empname;
	
	public int getEmpid() {
		return empid;
	}
	public void setEmpid(int empid) {
		this.empid = empid;
	}
	public String getEmpname() {
		return empname;
	}
	public void setEmpname(String empname) {
		this.empname = empname;
	}
	
}

public class Company 
{
	public static void main(String args[])
	{
		Employee e = new Employee();
		e.setEmpid(52);
		e.setEmpname("Hamid");
		System.out.println("Employee id: "+ e.getEmpid());
		System.out.println("Employee name: "+ e.getEmpname());
	}

}

Output:


Employee id: 52
Employee name: Hamid

Explanation:


The Employee class is developed in the above Java program, and the empid and empname variables are specified as private modifiers within this class.


The get methods, such as getEmpid() and getEmpname(), are public and are used to retrieve the variables.


Setter methods, such as setEmpid() and setEmpname(), are also public and are used to set the values of variables.


The set method assigns the empid and empname variables to two parameters (empid and empname). This keyword refers to the currently selected objects.


Our class fields can be read-only or write-only using the getter and setter methods.


The object of class Employee is generated in the class Company, and values for empid and empname are passed through the object. The "e" is the object.


The object then gets variable values and outputs both values using the System.out.println() command.


Advantages of Encapsulation in Java

The encapsulation technique makes the encapsulated data more secure. Because encapsulation stops external classes from accessing data members and data methods.


Encapsulation allows you to change code that has already been implemented without affecting other code.


It enhances reusability and makes it simple to adapt to new requirements.


The fields can be made read-only if the setter method is not defined in the class.


The fields can be made write-only if the getter method is not defined in the class.


Unit testing is simple with encapsulated code.


Getters and setters are supported by most IDEs, making coding even faster.


Data Hiding in Java

As part of the OOP technique, data hiding was implemented.


Data hiding is a key principle of object-oriented programming systems (OOPs) in Java.


It makes it impossible to access variables (data members) from outside the class, ensuring data security. In Java, this oops feature is known as data hiding.


Encapsulation and data hiding are commonly used similarly. However, they are not the same. 


Encapsulation in Java refers to the grouping of similar data into a single unit for improved data management and security.


On the other hand, data hiding prevents data member access by hiding implementation details. While encapsulation isn't quite data hiding, it does allow us to hide data.


How to achieve Data Hiding in Java?

Access modifiers are used to hide data.


There are four access modifiers in Java.


Default:


If no access specifier is specified for any Java class, the compiler will use 'default' as the access specifier. Only the package has access to the default modifier.


Public:


The public access specifier permits access to a class from any place in the program.


It can be accessed from within and outside the class, as well as from within and outside the package.


package MyPackage;

class Person 
{
	public int age;
	
	public void display()
	{
		System.out.println("My name is Jhon");
		System.out.println("I'm " + age + " years old ");
	}
}
public class Persondisplay
{
	public static void main(String args[])
	{
		Person p = new Person();
		p.age = 20;
		p.display();
	}
}

Output:


My name is Jhon
I'm 20 years old 

Private:


The data members are accessible via the private access specifier, and the data methods are restricted to the class itself.


package MyPackage;

class Student
{
	private int rollno;

	public int getRollno() {
		return rollno;
	}

	public void setRollno(int rollno) {
		this.rollno = rollno;
	}
}


public class Studentdisplay 
{
	public static void main(String args[])
	{
		Student s = new Student(); // create an object of Student class 
		s.setRollno(52); // change roll number using setter
		System.out.println("A student roll number is:- " +s.getRollno()); // get roll number using getter
	}

}

Output:


A student roll number is:- 52

Explanation:


We have a private field called rollno in the Java program above. It can't be accessed from outside the class because it's private.


We utilized public methods to retrieve rollno: getRollno() and setRollno() (). These are known as getter and setter methods.


We are able to limit unwanted access from outside the class by making rollno private. This method is known as data hiding.


Protected:


Only by inheritance, i.e. by creating subclasses or derived classes, may the protected modifier be accessed from within and outside the package.


The private and secured access specifiers are similar. The primary difference is that instead of only a class with the private access specifier, the access is limited to the entire package.


As a result, it is less restricted than the private modifier.


The protected modifier enables subclasses to use the assistance method or field while blocking it from being used by unrelated classes.



package MyPackage;

class User
{
	protected String name;
	
	protected void show()
	{
		System.out.println("This is " + name + " and founder of Apple Company");
	}
}

public class Founder extends User
{
	public static void main(String args[])
	{
		User  u = new User();
		u.name = "Steve Jobs";
		u.show();
		
	}

}

Explanation:


We have the User class in the above example, and we have specified the name field and show method as protected specifiers within this class. They are not accessible outside of the class.


The Founder class, which is the child class, is created next. We use the extends keyword in this class to access our User or parent class.


After that, we create the User class object, pass the filed data to it, and call the show method with it.


Finally, the following output appears.


Output:


This is Steve Jobs and founder of Apple Company

Why Do We Need Encapsulation

Encapsulation enables us to alter the code or a piece of the code without affecting other functions or code.


Encapsulation gives you complete control over the class's data members and data methods.


The way we access data is controlled by encapsulation.


Encapsulation blocks external classes from accessing data members and data methods. The encapsulation approach makes the encapsulated data more secure.


Modern IDEs provide built-in support for 'Getter and Setter' methods, which speeds up development.


Difference Between Abstraction and Encapsulation In Java

AbstrationEncapsulation
This feature is designed to hide codes from users that are irrelevant or redundant.This feature can be used to combine many codes into a single unit.
At the design level, abstraction solves an issue.At the implementation level, encapsulation solves an issue.
The external features benefit from abstraction.Internal features are improved via encapsulation.
Encapsulated objects are used to achieve abstraction.Encapsulation does not require abstraction.
This feature can be implemented using abstract classes and interfaces.This feature is implemented using access modifiers.
The presentation improves with abstraction.Encapsulation improves the method's maintainability.
Abstraction has no effect on unit testing.Encapsulation makes unit testing easier.

Tightly Encapsulated Class in Java

In Java, a tightly encapsulated class is one in which each variable is specified as private.


We are not needed to verify whether the class contains getter and setter methods, or whether these methods are declared public or not, for strongly encapsulated classes.


public class Product
{
 private double price;
 
 public double getprice()
 {
   return price;
 } 
 
}

To grasp the concept of tightly encapsulation, use the examples below.


Example,


Class X and Class Z are two classes that are tightly encapsulated. Because of non-private variable b, Class Y is not a tightly encapsulated class. It is directly accessible from outside the class.


class X 
{
	private int a = 20;
}
class Y extends X
{
	int b = 50;
}
class Z extends X
{
	private int c = 10;
}

Let's see the next example,


Because class J is the child class of I, none of these are tightly encapsulated classes.


By default, non-private data members of class I are available in subclass J.


In the same way, class K is a subclass of J. By default, all non-private data members of class J are visible inside class K.


class I 
{
	int a = 10;
}
class J extends K 
{
	private int b = 20;
}
class K extends J 
{
	private int x = 30;
}

Frequently Asked Questions

A Real-Time example of encapsulation in Java?


Realtime Example,


One of the most basic examples of Encapsulation is a laptop bag. Our laptop, charger, and other supplies can all be kept in a laptop bag.


What are the Three Types of Encapsulation?


Encapsulation can be divided into three categories.


1. Member Variable Encapsulation


All data variables should be defined as Private members of the Class in Object-Oriented Programming.


Any object that needs to update the value of a data member should utilize the Setters and Getters methods. You've already known of Data Member Encapsulation.


2. Function Encapsulation


Private methods that are only used to implement internal APIs must always be specified.


To stop the user from accessing the method, it should be defined as a Private method.


Make sure to hide any function that does not require public access.


3. Class Encapsulation


Internal API implementations that follow the same principles are used.


Any API's public interface should not include these classes. They should be hidden from your users and kept private.


For example, your API could have a class that applies specified data. If your user does not have access to that information class, you should encapsulate it by declaring it a Private class.


What is Data Hiding?


Data Hiding is an essential feature of Object-Oriented Programming (OOP) that allows developers to protect sensitive data while also hiding implementation information from unknown sources.


What is the Basic Difference Between Encapsulation and Data Hiding?


The primary difference between encapsulation and data hiding is that encapsulation is a method of bundling data, while data hiding blocks unauthorized access to critical data from the outside.

No comments:

Post a Comment

Post Bottom Ad