Encapsulation means to bind things into one object. For example into capsule we put many medicines.
Encapsulations is also one of the very great feature of JAVA.
We bind all the data members of class into one Class is called Encapsulations.
But what is the need to encapsulate the data members?
The only reason is to make data initialization more accurate. For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class UserProfile{ private String name; private int age; public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } } |
Here UserProfile class is the example of encapsulation. Into this class, we have made its data members private, so that other classes won't able to initialize them directly or can not get there values directly. Right now we haven't defined getters for data members, but defined setters.
Now, if we want to make a validation here,
- name should not be null
- age should be greater then 18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | public class UserProfile{ private String name; private int age; private UserProfile(){ } public UserProfile(String name, int age) throws Exception{ setName(name); setAge(age); } public void setName(String name) throws Exception{ if(name==null){ throw new Exception("Name should not be null"); } this.name = name; } public void setAge(int age) throws Exception{ if(age<18){ throw new Exception("Age should not be less then 18"); } this.age = age; } public String getName(){ return name; } public int getAge(){ return age; } } |
Now, UserProfile class is strongly encapsulated. at-least we can say that 😉
Here we have made default constructer private, so that there should be no any default values into the data members.
For instantiate the object of UserProfile, we have made parameterized constructor. It is helpful to make sure that each data members have there value.
Now, we have made a small changes into setters of data members. Now they have conditions according to there validations, and if validation fails, they throw an Exception.
Ooh wow, exception handling we have used here, also one of my favorite feature of JAVA.
Well now it gives us surety that the data member will have their either correct value, or throw an exceptions, which will handle accordingly by the caller.
No comments:
Post a Comment