Encapsulation in Java is a mechanism of wrapping
the data (variables) and code acting on the data (methods) together as a single
unit. In encapsulation, the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.
- We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
- The Java Bean class is the example of fully encapsulated class.
- By providing only setter or getter method, you can make the class read-only or write-only.
- It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
Example Program:
EncapsulationTest .java
import java.util.*;
public class EncapsulationTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
String designation = scan.nextLine();
String department = scan.nextLine();
Student s = new Student();
s.setName(name);
s.setDesig(designation);
s.setDepart(department);
System.out.println(" The Name of the Student is : " + s.getName() + " The Desig of the Student is : " +s.getDesig()+" The department of the Student is : " + s.getDepart());
}
}
Student.java (put these code in a separate file or put it in a EnhanceTest.java)
public class Student
{
private String name,desig,depart;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDepart()
{
return depart;
}
public void setDepart(String depart)
{
this.depart = depart;
}
public String getDesig()
{
return desig;
}
public void setDesig(String desig)
{
this.desig = desig;
}
}
No comments:
Post a Comment