Java Encapsulation2 min read

Encapsulation is one of the four fundamental OOP concepts. Encapsulation in Java is defined as the wrapping up of data(variable) under a single unit. The use of Encapsulation is to make sure that implementation detail or we can say sensitive data is hidden from the users. For this, Encapsulation is also known as data hiding.

Implementing the encapsulation in the program, the variables or data declared in one of the classes is hidden from any other class.

Encapsulation can be achieved in two ways:

  • Declare class variables/attributes as private, restricting other classes to access it.
  • Provide public setter and getter methods to modify and view the values of the variables.

Benefits of Encapsulation:

  • Data- hiding in Java.
  • The class field can be made read-only or write-only.
  • It provides the class the total control over the data.

Get and Set:

As we know the private variable cannot be accessed by other classes, but we can access them by providing getter and setter methods.

  • The get method returns the variable value.
  • The set method sets the value.

Note:
Getter and Setter methods should start with get or set, followed by the variable name whose first letter should be in upper case. They both should be declared public. Since get returns value and set doesn’t get should be of data-type same as the variable it accesses and set must be declared void.

Syntax Example:

Let us go through a java example to understand better


Encapsulation in Java using setter and getter

Output:

Student Id: 1101
Student Name: Marshall
Student Age: 20


MORE

Implement Insertion sort Program in C

In this tutorial, we will learn and write a C program to implement insertion sort. Before that you may go through the following topics in …
Read More

C Program for implementation of Selection sort

In this tutorial, we will learn and write a C program to implement selection sort using function. Before that you may go through the following …
Read More

C Program to Delete a Particular element from an Array

In this tutorial, we will write a C program to delete an element in an array by specifying the value. Before that, you should have …
Read More

C Program to sort a String in Ascending order

In this tutorial, we will write a c program to sort a string array in ascending order. Before that, you may go through the following …
Read More

C Program to find Maximum occurring Character in a String

In this tutorial, we will write a program in C to find the maximum occurring character in a string. Before that, you may go through …
Read More

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More