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

C Program to search an element in an array using Pointers

A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array …

C Program to find the sum of the digits of a number using recursion function

This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation: Function Definition: sumDigits(int n) This function calculates …

C program to find factorial of a numberĀ using Ternary operator with Recursion

Recursion refers to the function calling itself directly or in a cycle. Before we begin, you should have the knowledge of following in C Programming: …

C Program to Add Two Numbers Using Call by Reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through …

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …