Sie sind auf Seite 1von 1

Home All Tutorials Core Java OOPs Collections Java I/O JSON DBMS

Encapsulation in Java with example


Java Tutorial Search this website
BY CHAITANYA SINGH | FILED UNDER: OOPS CONCEPT
Java Index

Java Introduction Encapsulation simply means binding object state( elds) and behaviour(methods) together. If you are
creating class, you are doing encapsulation. In this guide we will see how to do encapsulation in
JVM - Java Virtual
java program, if you are looking for a real-life example of encapsulation then refer this guide: OOPs
Machine
features explained using real-life examples.
First Java Program

Variables For other OOPs topics such as inheritance and polymorphism, refer OOPs concepts
Data Types
Lets get back to the topic.
Operators

Java Control What is encapsulation?


Statements
The whole idea behind encapsulation is to hide the implementation details from users. If a data
Java If-else
member is private it means it can only be accessed within the same class. No outside class can
Java Switch-Case access private data member (variable) of other class.
Java For loop

Java while loop

Java do-while loop

Continue statement

break statement

OOPs Concepts

OOPs Concepts

Constructor

Static keyword
However if we setup public getter and setter methods to update (for example void setSSN(int
Inheritance ssn))and read (for example  int getSSN()) the private data elds then the outside class can access
Types of inheritance those private data elds via public methods.
Aggregation
This way data can only be accessed by public methods thus making the private elds and their
Association
implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets
Super Keyword see an example to understand this concept better.
Method overloading

Method overriding Example of Encapsulation in Java


Overloading vs
How to implement encapsulation in java:
Overriding
1) Make the instance variables private so that they cannot be accessed directly from outside the
Polymorphism class. You can only set and get values of these variables through the methods of the class.
Types of 2) Have getter and setter methods in the class to set and get the values of the elds.
polymorphism
class EncapsulationDemo{
Static and dynamic
private int ssn;
binding private String empName;

Abstract class and private int empAge;

methods
//Getter and Setter methods
Interface public int getEmpSSN(){
return ssn;
Abstract class vs }
interface
public String getEmpName(){
Encapsulation
return empName;
Packages }

Access modi ers


public int getEmpAge(){
Garbage Collection return empAge;
}
Inner classes
public void setEmpAge(int newValue){
Static import
empAge = newValue;
Static constructor }

Java Interview Q
public void setEmpName(String newValue){
empName = newValue;
MORE ...
}

Java 8 Features
public void setEmpSSN(int newValue){
Java 9 Features ssn = newValue;
}
Java Conversion
}
Java String public class EncapsTest{
public static void main(String args[]){
Exception handling EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
Java Multithreading
obj.setEmpAge(32);
Java I/O obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
Java Serialization
System.out.println("Employee SSN: " + obj.getEmpSSN());
Java Regex System.out.println("Employee Age: " + obj.getEmpAge());
}
Java AWT }
Java Swing
Output:
Java Enum

Java Annotations Employee Name: Mario


Employee SSN: 112233
Employee Age: 32

In above example all the three data members (or data elds) are private(see: Access Modi ers in
Java) which cannot be accessed directly. These elds can be accessed via public methods only. Fields
empName, ssn and empAge are made hidden data elds using encapsulation technique of OOPs.

Advantages of encapsulation
1. It improves maintainability and exibility and re-usability: for e.g. In the above code the
implementation code of void setEmpName(String name) and String getEmpName() can be
changed at any point of time. Since the implementation is purely hidden for outside classes
they would still be accessing the private eld empName using the same methods
(setEmpName(String name) and getEmpName()). Hence the code can be maintained at any
point of time without breaking the classes that uses the code. This improves the re-usability of
the underlying class.
2. The elds can be made read-only (If we don’t de ne setter methods in the class) or write-only
(If we don’t de ne the getter methods in the class). For e.g. If we have a eld(or variable) that
we don’t want to be changed so we simply de ne the variable as private and instead of set and
get both we just need to de ne the get method for that variable. Since the set method is not
present there is no way an outside class can modify the value of that eld.
3. User would not be knowing what is going on behind the scene. They would only be knowing
that to update a eld call set method and to read a eld call get method but what these set
and get methods are doing is purely hidden from them.

Encapsulation is also known as “data Hiding“.

❮ Previous Next ❯

Comments

sowrag says
MAY 6, 2014 AT 6:29 PM

i am confused about when doGet() and doPost() methods are used ,plz could u clarify my
doubt

Reply

Ather says
SEPTEMBER 16, 2014 AT 3:53 PM

We use doPost() method when we dont want the data(while submitting a form) to
be send through the URL while in doGet() form data is sent though URL

Reply

Asiri says
NOVEMBER 6, 2014 AT 7:57 PM

i am really confused, in java we cannot have two public methods in a same source
le. one method should only be public.

Reply

Chaitanya Singh says


NOVEMBER 15, 2014 AT 8:21 AM

@Asiri, No we can have any number of public methods in a class. We cannot


have more than one public class in the same source le.

Reply

Anish says
MAY 16, 2016 AT 5:27 AM

doGet() vs doPost() methods are used to change implementation of form, such as


doGet() method exposed the all form submitting data into URL bar at page run
time.and doPost() method not exposed form data in url bar at run time its more
secureful……its my according….

Reply

shyamal says
SEPTEMBER 29, 2014 AT 6:21 AM

Thanks for very good post

Reply

Anonymous says
NOVEMBER 6, 2014 AT 6:16 AM

Hi,

Thanks for this post. This is really good and easy to understand. But, can you please
explain this with a real time scenarios. because this is easy to understand but how
practically this is useful. And where exactly this is needed.

Thanks.

Reply

anitha says
FEBRUARY 17, 2015 AT 6:20 AM

Hi
I can understand the concept of encapsulation and program. But how could u say that. It
hide the data but we can use the function. And I have a doubt is so that without using
get and set method we can’t achieve encapsulation.

Reply

Harsha vardhan says


MAY 30, 2015 AT 2:14 PM

public class Encapsulation1{


public static void main(String args[]){
Encapsulation obj = new Encapsulation();
obj.setEmpName(“Mario”);
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println(“Employee Name: ” + obj.getEmpName());
System.out.println(“Employee SSN: ” + obj.getEmpSSN());
System.out.println(“Employee Age: ” + obj.getEmpAge());
}
When i am executing above code.the following error has been occurring.Help me to
solve this error …This is Error i am getting.
The public type Encapsulation1 must be de ned in its own le

Reply

sachin says
MARCH 13, 2016 AT 6:53 PM

Encapsulation obj = new Encapsulation(); //is error

Encapsulation1 obj = new Encapsulation1(); //recti ed

Save the le name as Encapsulation1.java

Reply

Rshan says
OCTOBER 7, 2016 AT 7:00 PM

you can not use the key word encapsulation..


so you can rename it with any other name….

Reply

Randy Dickinson says


JULY 3, 2015 AT 2:14 AM

very good explanation of encapsulation and how and why it works nice job

Reply

aditya raghuwanshi says


OCTOBER 1, 2015 AT 6:32 AM

what is the difference between abstraction and encapsulation while they both are hiding
the implementation from user.plz answer me.

Reply

Ranjeet Singh says


DECEMBER 26, 2015 AT 9:27 AM

“Abstraction is implemented using interface and abstract class while Encapsulation


is implemented using private and protected access modi er.”

Reply

DKL says
FEBRUARY 11, 2016 AT 7:51 PM

Abstraction identi es which information should be visible as well as which


information should be hidden. Encapsulation packages the information in such a
way as to hide what should be hidden, and make visible what is intended to be
visible. I hope that helps.

Reply

kiran M Patel says


SEPTEMBER 3, 2017 AT 6:32 AM

we use abstraction when we are not sure about certain implementation.


for e.g -> car surely need fuel but may or maynot need ac & wiper features.
so we de ne implementation for only fuel() and make ac(),wiper()as abstract.i.e no
implementation.

encapsulation-> provides data protection/hiding.


->Technically in encapsulation, the variables or data of a class is hidden from any
other class and can be accessed only through any member function of own class in
which they are declared.
-> Encapsulation can be achieved by: Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of
variables.

Reply

janardhan says
NOVEMBER 7, 2015 AT 4:57 AM

can you please explain the difference between the terms–>


Bean,POJO,JavaBean,EJB,Entity,DataTransferObject,springBean–

Reply

ravi says
APRIL 14, 2016 AT 10:08 AM

can you please explain the difference between the private public an protected and
encapsulation inheritance and polymorphism with simple examples?

Reply

rajeshkumar says
MAY 29, 2016 AT 5:42 AM

@Ravi… Hi, for Public modi er we can access the methods or varibles from another
class to another class. But when we going for Private Modi er we can’t access from
another class but we can access within the class.

Inheritance: There is a class called Class A and Class B. We can use the Class A
methods in Class B by using the extends Keyword. For eg. public class classA
{public static void add(){…}
}
public class classB extends class A
{
public static Void sub(){…}
public static void main(String[] args){ add();sub()}}

Reply

Ankit says
MAY 31, 2016 AT 7:07 PM

Very nice article.

One question:
Within a single le 2 (two) public class is possible ?

As per my knowledge only one public class we can declare .

Reply

Krupen Ghetiya says


JUNE 9, 2016 AT 5:36 PM

To make variables read-only, you can also declare them as “ nal” and set them in
constructor, making them private is not the only way :) .

Reply

Parnika says
APRIL 17, 2018 AT 12:00 PM

Nice tutorial for beginners.


I have a doubt in Encapsulation which confuses us all the time. Encapsulation means
Data hiding, for that we are declaring data members so that outside class cannot access.
[Security purpose].
But here when other classes can access those values through setter and getters
methods, then where is security lies here. Why to hide data with private speci er and
why to access with setter and getter methods?

Reply

Chaitanya Singh says


APRIL 19, 2018 AT 12:02 PM

The main difference between making a data member public vs. accessing it using
getter setter methods is taking the control over the data members.
By making a eld public, you are allowing the direct access. This way anyone can
change the value of the eld without any validation, for example anyone can set a
data member to null, even if it is not supposed to be null. You have no control here.
The same thing when you do with the help of setter method then you can have a
validation check in the setter method itself to not set the value of the eld if it is
supplied as null.
Hope this helps.

Reply

Leave a Reply
Your email address will not be published. Required elds are marked *

Comment

Name *

Email *

POST COMMENT

Copyright © 2012 – 2020 BeginnersBook . Privacy Policy . Sitemap

Das könnte Ihnen auch gefallen