The Best Technical Blog Ever

twitterrss

Encapsulation in Java

Encapsulation is the process of wrapping data and methods into a single unit (i.e. class) in order to protect against external interference and misuse. It prevents the data from the outside world (other code defined outside the class) and only those methods which are enclosed in the same class can access it.


encapsulation


By declaring the data members as private, we can restrict the access of these data members from outside class. Since within the same class only we can access them. However, outside classes can access the private data member by using the public getter and setter methods. In that way, it hides details from the user, so it is also called as data hiding.


encapsulation


Lets see a simple encapsulation example.


encapsulation


In the above example, customer_name and account_balance are private data members. To access these private details, public methods like withdraw(), deposit(), miniStatement() are used. These methods protect the private details from external access


Example:

Book.java


encapsulation


EncapsulationSample.java


encapsulation


encapsulation


Here we are using public methods (setName, getName..) to access the private data members. First we sent values to data members using setter methods, finally values are retrieved using getter method. To understand how encapsulation works, lets see the below diagram of Bank class.


encapsulation

Benefits of Encapsulation:

Encapsulation protects an object from unauthorized access and allows you to control who can access what. It hides the implementation details of an object and increases reusability. It also helps the developer to make the code more flexible and maintainable by binding the data and methods in a single unit. With the encapsulation, we can change one part of the code easily without affecting the other part of the code


Keypoints to remember in java

1. Java is a high level, robust, secured , platform independent and object oriented programming.... more info

Back to Basics:- Java Syntax

In this session, you are going to refresh some basic set of rules(java syntax), defining how a ... more info

Total Visits
Traffic feed status