Table of Contents
In this tutorial, we will discuss the concept of the Encapsulation in Java programming language
Encapsulation is one of the most important concepts of Oop programs. Other some Oop concepts are inheritance, polymorphism and abstraction
Basically, It is used for security purposes in Java. We can use it in ATM, password protection…
Encapsulation means binding data members and methods into a single unit with data security. It helps to hide the implementation details from the user. If the data members are private, it can only be accessed from the same class.
No one outside the class can access private data members(variable) of other classes. It is known as data-hiding in java. Encapsulation of the variables of ` class will be hidden from other classes.
However, we can setup a getter and setter method. We can make the class read-only or write-only.
To use encapsulation in Java, you must declare the data members of a class as private(for security).
Advantages of Encapsulation
It improves maintainability and flexibility and re-useability.
The user would not know what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get method are doing is purely hidden from them
How does encapsulation work in Java
Encapsulation works in Java with the following reasons
Declaring the properties or variables as private – Encapsulation can be achieved by Declaring all the properties or variables as private. these variables can be accessed by public methods of the class
For example, we are creating a class student. the variable must be declared as private
private string stu_Name
private int stu_Id;
provate int stu_Marks;
Create public methods inside the class in order to get and set(getter and setter) the attributes or variables
public string get_stu_Name(){ return stu_Name; } public int get_stu_Id(){ return stu_Id; } public int get_stu_Marks(){ return stu_Marks; } public void set_stu_Name(string stu_Name){ this.stu_Name=stu_Name; } public void set_stu_Id(int stu_Id){ this.stu_Id =stu_Id; } public void set_stu_Marks(int stu_Marks){ this.stu_Marks=stu_Marks; }
Program 1
Program 2
Program 3
When the above code is executed it produces the following result
Abstraction in C++ Abstract class in Java
Polymorphism in C++ Methodoverriding in Java
Subtract two numbers using method overriding Program 1
PHP Star triangle Pattern program Here's a simple Java program that demonstrates how to print…
Using Function or Method to Write to temperature conversion: Fahrenheit into Celsius In this article,…
Function or method of temperature conversion from Fahrenheit into Celsius In this article, we will…
Write temperature conversion program: from Fahrenheit to Celsius In this article, we will discuss the…
How to write a program to convert Fahrenheit into Celsius In this article, we will…
This website uses cookies.