21 Understanding Encapsulation Using Examples
21 Understanding Encapsulation Using Examples
In this lesson, you will get a rmer understanding of encapsulation in Java with the help of examples.
• A Bad Example
• A Good Example
The goal is to prevent this bound data from any unwanted access by the code
outside this class. Let’s understand this using an example of a very basic User
class.
Whenever a new user comes, a new object can be created by passing the
userName and password to the constructor of this class.
class User class Main
main(){
String userName
String password new User
new User
A Bad Example #
Now it is time to implement the above discussed User class.
class User
+String userName
+String password
+ void login()
// User Class
class User {
// Public Fields
public String userName;
public String password;
class Main {
educative.login("Educative", "3456"); //Does not grant access because the credentials are
educative.login("Educative", "3456"); // GRANTS ACCESS BUT THIS SHOULD NOT HAVE HAPPENED!
}
In the above coding example, we can observe that anyone can access, change
or print the password and userName fields directly from the main() method.
This is dangerous in the case of this User class because there is no
encapsulation of the credentials of a user and anyone can access their account
by manipulating the stored data. So the above code was not a good coding
convention.
A Good Example #
Let’s move on to a good convention for implementing the User class!
class User
-String userName
-String password
+ void login()
// User Class
class User {
// Private fields
private String userName;
private String password;
class Main {
educative.login("Educative", "3456"); //Does not grant access because the credentials are
}
In the above example, the fields of userName and password are declared
private .
This is the concept of encapsulation. All the field containing data are private
and the methods which provide an interface to access those fields are public.
Now let’s test your understanding of encapsulation with the help of a quick
quiz!