Previous | Home | Next |
Encapsulation is a bundling of member variable and member method together in a class as a single entity is known as called as encapsulation. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. for example capsule i.e. mixed of several medicines. Data Hiding is declaring a member has private we can hide them from external objects. The Java Bean class is the example of fully encapsulated class.
Benefits of Encapsulation:
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.
Example :
import java.util.Scanner; class B { private int x; private float y; void getData()//for user input { Scanner sc; sc=new Scanner(System.in); System.out.print("Enter Value Of x :"); x=sc.nextInt(); System.out.print("Enter value of y :"); y=sc.nextFloat(); } void setdata(int x1,float y1)//for testing purpose { x=x1; y=y1; } void display() { System.out.println(x+","+y); } } class BTest { public static void main(String args[]) { B a1,a2; a1=new B(); a2=new B(); //a1.x=5 ;//error //a1.getdata(); //a2.gatdata(); a1.setdata(10,10.5f); a2.setdata(2,5.4f); a1.display(); a2.display(); } }
output :
10,10.5 2,5.4
Previous | Home | Next |