Data Encapsulation in Java

Hello friends how are you, today in this blog i will teach you what is Encapsulation , how to create encapsulation program, how encapsulation works and many programs using encapsulation in a very simple way. 

Let's start

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
*/


Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. 

Thanks.😊

Post a Comment

0 Comments