Java Encapsulation :
Java encapsulation is a process of wrapping up of data members and member function.Don’t get it no worries read the blog till the end and you will clearly understand this concept.
A basic example of en-capsule it to cover or enclose something within it just as a protection from outer surface.
Why do we need this in java???
Java encapsulation provides a security feature to the variables declared in the class by making them accessible only through the methods declared for them.
In general we will declare some variables in class we can access them directly with the class object and assign values to them or update existing values and what not but do you observe loop hole here…
If any one can change the values of variables there need to be some restrictions or at least a log needs to be maintained right so that how many times a variable is re assigned a new value.
Let’s see the normal way first without java encapsulation****
Consider a User class and declare few variables
class User { int id; String name; String email; }
Now we can access these variables from Store class as
class Store { public static void main(String args[]){ User user = new User(); user.id = 1; user.name = "abhi"; user.email = "abhi@gmail.com"; } }
Now we can’t trace any changes to values of variables and no security to variables even.
So here comes our java encapsulation concept where we declare variables as “private” and access them from methods.
Declaring private you can’t access them directly and you need some methods, and the methods used here are called Getter and Setter.
Getter:
Is used to fetch the value of a variable
public String getName() { return name; }
Setter:
Is used to set a value to a variable.
public void setName(String name) { this.name = name; }
Now the updated User class is
class User { private int id; private String name; private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
And to set and get data to it we will access through a object of class
user.setId(1); user.setName("abhi"); user.setEmail("abhi@email.com");
user.getId(); user.getName(); user.getEmail();
class Store { public static void main(String args[]) { User user = new User(); user.setId(1); user.setName("abhi"); user.setEmail("abhi@email.com"); System.out.println(user.getId()); System.out.println(user.getName()); System.out.println(user.getEmail()); } }
If you have any query on java encapsulation let us know in the comment section below.
Do like and share the tutorial for more interesting tutorials.