BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Encapsulation in Java with example

By Chaitanya Singh | Filed Under: java

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

For other OOPs topics such as inheritance and polymorphism, refer OOPs concepts

Lets get back to the topic.

What is encapsulation?

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

However if we setup public getter and setter methods to update (for example void setSSN(int ssn))and read (for example  int getSSN()) the private data fields then the outside class can access those private data fields via public methods.

This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see an example to understand this concept better.

Example of Encapsulation in Java

How to implement encapsulation in java:
1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.

class EncapsulationDemo{
    private int ssn;
    private String empName;
    private int empAge;

    //Getter and Setter methods
    public int getEmpSSN(){
        return ssn;
    }

    public String getEmpName(){
        return empName;
    }

    public int getEmpAge(){
        return empAge;
    }

    public void setEmpAge(int newValue){
        empAge = newValue;
    }

    public void setEmpName(String newValue){
        empName = newValue;
    }

    public void setEmpSSN(int newValue){
        ssn = newValue;
    }
}
public class EncapsTest{
    public static void main(String args[]){
         EncapsulationDemo obj = new EncapsulationDemo();
         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());
    } 
}

Output:

Employee Name: Mario
Employee SSN: 112233
Employee Age: 32

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

Advantages of encapsulation

  1. It improves maintainability and flexibility 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 field 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 fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) that we don’t want to be changed so we simply define the variable as private and instead of set and get both we just need to define 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 field.
  3. User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them.

Encapsulation is also known as “data Hiding“.

❮ PreviousNext ❯

Comments

  1. 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 file. 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 file.

        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
  2. shyamal says

    September 29, 2014 at 6:21 AM

    Thanks for very good post

    Reply
  3. 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
  4. 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
  5. 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 defined in its own file

    Reply
    • sachin says

      March 13, 2016 at 6:53 PM

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

      Encapsulation1 obj = new Encapsulation1(); //rectified

      Save the file 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
  6. Randy Dickinson says

    July 3, 2015 at 2:14 AM

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

    Reply
  7. 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 modifier.”

      Reply
    • DKL says

      February 11, 2016 at 7:51 PM

      Abstraction identifies 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 define 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
  8. 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
  9. 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 modifier we can access the methods or varibles from another class to another class. But when we going for Private Modifier 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
  10. Ankit says

    May 31, 2016 at 7:07 PM

    Very nice article.

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

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

    Reply
  11. Krupen Ghetiya says

    June 9, 2016 at 5:36 PM

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

    Reply
  12. 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 specifier 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 field public, you are allowing the direct access. This way anyone can change the value of the field 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 field if it is supplied as null.
      Hope this helps.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap