Java Oops - Encapsulation in java

Encapsulation in java :

  1. The process of combining many elements into a single entity is called Encapsulation. Or In the field of the 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 feature 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 that is used to provide accessibility of data member(variable) and member function(function) of a class.
  2. It is also called an access modifier.


Types of Access Specifiers:

There are three types of access specifiers.

  1. Public
  2. Private
  3. Protected

public

1. It allows the accessibility of data member and member function to the other classes.

2. a public element of a class can be accessed anywhere in the program.

private

1. It is used to hide data member and member functions from the other classes.

2. a private element of a class can be accessed only inside its own class. 

3. a private element of a class can not be accessed out of that class.

protected

1. It is approximately the 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 :

1:  //simple interest=(p*r*t)/100  
2:  import java.util.Scanner;  
3:  class SimpleInterest  
4:  {  
5:  Scanner in=new Scanner(System.in);  
6:  //Data Member   
7:  float p;  
8:  float r;  
9:  float t;  
10:  float si;  
11:  //member function   
12:  void getPara()  
13:  {  
14:   System.out.println("Enter principle");  
15:   p=in.nextFloat();//taking input  
16:   System.out.println("Enter rate of interest");  
17:   r=in.nextFloat();//taking input  
18:   System.out.println("Enter time duration");  
19:   t=in.nextFloat();//taking input  
20:  }  
21:  void findInterest()  
22:   {  
23:   si=(p*r*t)/100;  
24:   }  
25:  void show()  
26:  {  
27:  System.out.println("Simple Interest="+si);  
28:  }  
29:   public static void main(String[] args)   
30:   {  
31:   //creating instance(object) of class  
32:   SimpleInterest obj=new SimpleInterest();  
33:   //calling function  
34:   obj.getPara();  
35:   obj.findInterest();  
36:   obj.show();  
37:   }  
38:  }  
39:  /*  
40:  ### Output ###  
41:  Enter principle  
42:  1500  
43:  Enter rate of interest  
44:  5.5  
45:  Enter time duration  
46:  8  
47:  Simple Interest=660.0  
48:  */