Encapsulation in Java.
Encapsulation
1.The process of combining many elements into a single entity is called Encapsulation.
or
In the field of programming language the process of combining data member and member function into a single entity like class is called Data encapsulation.
2.It is an important features of object oriented programming.
3.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
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 three types of access specifier.
- Public
- Private
- Protected
public
1.It allows the accessibility of data member and member function to the other classes.
2.public element of a class can be accessed anywhere in the program.
private
1.It is used to hide data member and member function from the other classes.
2.private element of a class can be accessed only inside in its own class. 3.private element of a class can not be accessed out of that class.
protected
1.It is approaximately same as private but it allows the accessibility of data member and member function to the child class.
2.protected is used in the case of inheritance.
Example of Encapsulation
//simple interest=(p*r*t)/100 import java.util.Scanner; class SimpleInterest { Scanner in=new Scanner(System.in); //Data Member float p; float r; float t; float si; //member function void getPara() { System.out.println("Enter principle"); p=in.nextFloat();//taking input System.out.println("Enter rate of interest"); r=in.nextFloat();//taking input System.out.println("Enter time duration"); t=in.nextFloat();//taking input } void findInterest() { si=(p*r*t)/100; } void show() { System.out.println("Simple Interest="+si); } public static void main(String[] args) { //creating instance(object) of class SimpleInterest obj=new SimpleInterest(); //calling function obj.getPara(); obj.findInterest(); obj.show(); } } /* ### Output ### Enter principle 1500 Enter rate of interest 5.5 Enter time duration 8 Simple Interest=660.0 */