Encapsulation in java
Encapsulation:
- The process of combining many elements into a single entity is called Encapsulation.
- In Another Word:-
- The process of combining data member and member function into a single entity like class is called Data encapsulation.
- It is an important features of object oriented programming.
- It is used to prevent the direct accessibility of data member and member function and this is done by using access specifier public,private and protected.
Access Specifier
I have already discuss in previous chapter in details what is access specifiers and some important example. ACCESS SPECIFIERS
1.It is a keyword which is used to provide accessibility of data member(variable) and member function(function) of a class.
2.It is also called access modifier.
Types of Access Specifier
There are Four types of access specifier.
Default Public Private Protected
Default :-
- The class is only accessible by classes in the same package. This is used when you don't specify a specifiers, You will learn more about packages in the Packages chapter.
Public :-
- It has no Security, that means public members can be provided to the interface to the external world so can be access from any where in the program.
Private :-
- It is most important and secure members(private) can be access only inside the class or type of access out-side the class.
- To hide the data members input the in private area
Protected:-
- It's less secure by private, protected members can be access by class member and by the members of derived class, that means we can say that protected members can be access inside the class and relatives class.
- Protected is used in the case of inheritance.
An Example of Encapsulation :
// Example 1: Find Simple Interest
class Encapsulation{
Scanner sc= new Scanner(System.in);
//Data Member;
float p;
float r;
float t;
float si;
// member function
void getsi(){
System.out.println("Enter Principal Value:- ");
p=sc.nextFloat();
System.out.println("Enter Time Value:- ");
t=sc.nextFloat();
System.out.println("Enter Rate Value:- ");
r=sc.nextFloat();
}
void siprocess(){
si=(p*r*t)/100;
}
void print(){
System.out.println("Your Simple Intrest Value:- "+si);
}
public static void main(String[] args){
Encapsulation obj= new Encapsulation(); // create an instance objects
obj.getsi();
obj.siprocess();
obj.print();
}
}
******Output*********
PS F:\Learning File\BCA\BCA 3rd Sem\JAVA OOP\BLOG> java Encapsulation
Enter Principal Value:-
1000
Enter Time Value:-
5
Enter Rate Value:-
6
Your Simple Intrest Value:- 300.0
I hope this is simple example for your better understanding of Encapsulation. Don't forget follow me.
Comments