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

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 …
Read More

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …
Read More

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …
Read More

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More

Inverted Half Pyramid Pattern of Alphabets in C

In this tutorial, we will write a C program to print half Pyramid using alphabets/characters. Before that, you may go through the following topic in …
Read More