Day - 14 - Encapsulation
Day - 14 - Encapsulation
Syntax:
private <Data_Members>;
private <Data_Methods>;
1 www.softtwig.com
Softtwig Technology Solution Private Limited
Better Control
Encapsulation provides ultimate control over the data members and data
methods inside the class.
Security
Encapsulation prevents access to data members and data methods by any
external classes. The encapsulation process improves the security of the
encapsulated data.
Flexibility
Changes made to one part of the code can be successfully implemented without
affecting any other part of the code.
2 www.softtwig.com
Softtwig Technology Solution Private Limited
Getter
The method capable of accessing and retrieving an instance of a private
variable is known as a getter method.
Sample:1
public class Student{
//private data member
private String college="AKG";
//getter method for college
public String getCollege(){
return college;
}
}
Setter
The method that is capable of modifying, or setting to an instance of a private
variable is the setter method.
Sample:1
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
3 www.softtwig.com
Softtwig Technology Solution Private Limited
}
}
By providing only a setter or getter method, you can make the class read-only
or write-only. In other words, you can skip the getter or setter methods.
913.6K
It provides you the control over the data. Suppose you want to set the value of
id which should be greater than 100 only, you can write the logic inside the
setter method. You can write the logic not to store the negative numbers in the
setter methods.
It is a way to achieve data hiding in Java because other class will not be able
to access the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters.
So, it is easy and fast to create an encapsulated class in Java.
4 www.softtwig.com
Softtwig Technology Solution Private Limited
5 www.softtwig.com