Java Encapsulation

Last modified on October 15th, 2014 by Joe.

Encapsulation is a concept in object oriented programming (OOP). It is nothing new and it is as popular as Harry Potter books among kids. I wrote a tutorial on relationships, like association, aggregation, composition, abstraction, etc and it was well received. I have been planning for long to write about all the OOPs concepts and this tutorial on encapsulation is one among that series.

Why is it titled Java encapsulation? Do we have something special for encapsulation in java? Let us be clear, encapsulation is a OOP concept and we will see an example of how it is implemented in Java. The key concepts in OOP are abstraction, encapsulation, inheritance and polymorphism and we will have a separate tutorial for each of these OOP concepts.

tortoise

Encapsulation Definition

Encapsulation is the ability to package data, related behavior in an object bundle and control/restrict access to them (both data and function) from other objects. It is all about packaging related stuff together and hide them from external elements.

We can see that keywords encapsulation and data hiding are used synonymously everywhere. It should not be misunderstood that encapsulation is all about data hiding only. When we say encapsulation, emphasis should be on grouping or packaging or bundling related data and behavior together.

encapsulation

When we design a class in OOP, the first principle we should have in mind is encapsulation. Group the related data and its behavior in a bucket. Primary benefit of encapsulation is, better maintainability.

That’s it! This is all about encapsulation. Let us leave it as simple as that. Nothing more and nothing less.

Encapsulation in Java

Any well defined Java class in its context domain is an example for encapsulation in Java. So the importance here is for bundling data and methods together only after that data hiding comes into picture. When we say data hiding, we all know about access specifiers in Java. Hiding an attribute or method is easier from the outer world. Just use the access specifier ‘private’.

So data hiding is fairly straight forward. How about bundling data and method. This is critical. We should understand well about the business domain and based on that design the class and group attributes and its methods together. This process is key in encapsulation.

Following is an outline example for Java encapsulation. When we talk about an animal, we should have all its attributes listed, similarly its behavior like how it will hunt, run, mate, etc. By bundling all these data and behavior in a single class we are following encapsulation principles.

package com.javapapers.java;

public class Animal {
	private String animalName;
	private String animalType;
	private int height;
	private String color;

	public Animal(String animalName, String animalType) {
		this.animalName = animalName;
		this.animalType = animalType;
	}

	public void hunt() {
		// implementation of hunt
	}

	public void run() {
		// implementation of run
	}

	public void mate() {
		// implementation of mate
	}
	//encapsulation is not about having getter/setters
	public String getAnimalName() {

		return animalName;
	}

	public void setAnimalName(String animalName) {
		this.animalName = animalName;
	}

	public String getAnimalType() {
		return animalType;
	}

	public void setAnimalType(String animalType) {
		this.animalType = animalType;
	}

}

There is a line of difference between abstraction and encapsulation, which we can easily understand with a simple example. We will see about that in the coming tutorial on abstraction. Practice encapsulation while you design the classes

Comments on "Java Encapsulation"

  1. Pratik says:

    Simple and Effective

  2. Kasuntha says:

    Here you described class’ methods are public and instance variables are private.Simply you allow to access the private variable through public methods. But the outsiders still can access them. So can you please describe the advantages of encapsulation further more? Thanks…

  3. Narendran Solai Sridharan says:

    Hi Joe,

    You could have added “Encapsulation” done in pattern such “encapsulation of Object creation” in Creational Pattern. “Encapsulation of Communication” in Mediator Pattern etc.,

    I have been an avid reader of all your blogs. You always have piqued my interest.

    Thanks. Keep Blogging.

  4. Pritam Maiti says:

    Thank you Joe for all your posts. They are simply of huge help.. Keep sharing like this.. I am looking forward to all your upcoming posts. Thanks

  5. Veera Reddy Sangham says:

    Hi Joe, Plz let me know answere for the following question: Here you described class’ methods are public and instance variables are private.Simply you allow to access the private variable through public methods. But the outsiders still can access them. So can you please describe the advantages of encapsulation further more?
    I am eagerly waiting for your reply. Thanks

  6. Praveen S M says:

    Its an abstraction concept which joe will explain in next class

  7. Praveen S M says:

    Its an abstraction concept which joe will explain in next class

  8. Anil says:

    Hi Joe,

    Nice article!!!.. but i have one doubt. We can hide the properties using private variables so outsiders can’t able to access them directly and change. But using Reflection they can change the values right. Then how can we say that our class is protected from others? Pls reply…

  9. rakesh says:

    but keeping the variables as private will refrain the other classes from accessing them.

  10. […] we ask for difference between encapsulation and abstraction, I would say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept […]

  11. gurumurthy says:

    Encapsulation is more about making the date secure. in terms of validating the date not only preventing from direct access.
    For validating,you have your own checks inside the public method.
    I hope ur question is clarified.

  12. Kieran says:

    2 reasons come to mind..
    1. You restrict access to private members by publishing a public API ie your public accessor methods. This allows you to modify the names / types and functionality under the hood in future without breaking your exported API – your dependent callers of your methods.
    2. Sometimes in multithreaded apps access to your members may need to be synchronized. You as the developer need to control exactly how or when your members can be accessed. For example you dont want direct access to your member when you are initializing the member via lazy initialization.

  13. Kieran says:

    Hi Joe, I feel you have left out a very valuable method of encapsulation and that is inner classes.

    static, non static and annonymous inner classes are a valuable way to encapsulate your data ensuring associated classes are bundled together away from view from the outside world.

  14. abdulshameer says:

    Hi VeeraReddy
    Hope you understand what Gurumurthy replied. Using accessor methods we can validate and prevent the illegal values to be set for the fields.

  15. Malathi says:

    Hi Kieran,

    Can you explain this with above example “This allows you to modify the names / types and functionality under the hood in future without breaking your exported API – your dependent callers of your method”. Functionality we can change without affecting the API, but how can we change the name/types without affecting API.

  16. Joe says:

    Thanks Narendran.

    I stopped with encapsulation in OOPS. Yes, it would be nice to have included encapsulation in creation, encapsulation in communication. I will try to update the content with these.

  17. Joe says:

    Sure Pritam. Welcome.

  18. Joe says:

    Veera,

    In encapsulation, more of the emphasis is on bundling data and method together. First this point should always come first than the data hiding.

    Yes, as Gurumurthy has commented, we may not expose data as-is in a functional object. We will have methods operating on it and will return its own output.

    In the case of a POJO or a simple value/transport object, the story is different. A transport object is just a carrier and the purpose there is to carry the data to different layers and nothing more. So there we will have getters/setters.

    Please read my next tutorial on abstraction also and it will complete this concept, https://javapapers.com/core-java/java-abstraction/

  19. Joe says:

    Anil,

    Java security manager’s checkPermission method is called before you can setAccessible to true for the field.

    Without security permission, we cannot read the value.

    Having said that, reflection is something that is not to be used for regular everyday programming. It is a powerful tool and it can be problematic too. When we bring reflection into picture, it unnecessarily complicates everything.

  20. Joe says:

    Thanks Grails cookbook, is that your name?

  21. Anonymous says:

    what is mean by partially/ completely encapsulated class?

  22. Shireesh says:

    Encapsulation is not about how you access the data, its all about how you protect your data.

    When you wrap your data with methods, these methods act as security for your data.
    Which means now you have total control over your data.

    For example :
    In public setter methods you can always include your validation logic so as to protect your data from accidental and unwanted modification.

    public void setSalary(final long salary){
    //Before setting data you can add your //validation logic here
    if(salary==0){
    throw Exception(“Salary Cannot Be 0”);
    }
    this.salary = salary;
    }

  23. Joe says:

    Yes Kieran, I agree. I will update the article with this reference. Thanks.

  24. Joe says:

    I do not see any formal reference to partially encapsulated class.

    If you find any, please let me know.

  25. Joe says:

    There is a difference, between exposing raw data of an object vs exposing the properties. Exposing properties is required. Raw data should be hidden by encapsulation. Kieran has added more below.

  26. Anonymous says:

    Actually, on the basis of complete & partial encapsulation 2-5 questions were asked in technical test which I had appeared. I didn’t get any reference for this. I am also searching it.

    In your above e.g. you have written //encapsulation is not about having getter/setters

    then
    Can we say that complete encapsulated class must have getter/setters and every variable declared in that class must be used in the same class(in its methods or by other way)?

  27. srinivas says:

    Hi, why we are using private in encapsulation,eventhough we are using private we are going to setting ,modifying the values using getters and setters so why cant we use public variables instead of private variables?

  28. srinivas says:

    Can you make encapsulation class as Singleton class?if yes please explain and write one example

  29. bageeradhasan says:

    its is bettrer

  30. […] object as it changes state. One important point to not in implementing memento design pattern is, the encapsulation of the object should not be […]

  31. Anonymous says:

    I have one doubt…

    We are writing variables as private & we can access them using setter and getter methods…we can change the variable value by using setter method then what is the use of writing variable as private…. one interviewer asked this question for me..

  32. rakesh says:

    gud explanation,,,thanxx joe!!!!

  33. Udhayakumar says:

    if we can access the private fields and methods through reflection then how data hiding is complete in java? can some one please clear my doubt.

  34. Anonymous says:

    can u please explain what is the use of writing variables as private in java encapsulation with example…

    thanks in advance…

  35. Sachin says:

    this is the best explanation regarding use of encapsulation.
    thanks alott

  36. […] Java Encapsulation Encapsulation is the ability to package data, related behavior in an object bundle and control/restrict access to them (both data and function) from other objects. […]

  37. manmeet kaur says:

    great job joe nyc explanation bt i also want to know its implementation

  38. Anonymous says:

    Consider having an age property and you want to have some control over it. If you expose your field simply as public, you can just access it externally and do whatever you want with it. Then, checking that the age is valid can be a little bit of a hassle.

    That being said, with a setter method, you could, for instance, have a verification mechanism in place. This provides you with control over how and when is your variable accessed and changed.

    The same applies for getter methods. Imagine you have some internal structure you do not want to expose, say, you use enumerations internally. However, you do not want to show this outside your class. So for instance, in your getter you yield the string version of whatever value you want to yield.

  39. chandu says:

    please send encapslation with bankaccount example

  40. Jagadeesh says:

    why we use private members in pojos

  41. Ruan Petterson says:

    Is that way recommended?

    [code]
    — public void get (String field) throws NoSuchFieldError {
    — — switch (field) {
    — — — case "name": return name;
    — — — case "age": return age;
    — — — case "height": return height;
    — — — default: throw new NoSuchFieldError(); // If the field inserted does not exist, it will show up an error
    — — }
    }
    [/code]

  42. Ruan Petterson says:

    Complete:

    [code]
    class Data {
    public static String regex (String regex, String input) throws IllegalArgumentException {
    if (Pattern.matches(regex, input)) {
    return input;
    } else {
    throw new IllegalArgumentException();
    }
    }
    }

    class Person {
    private String name;
    private String age;
    private String height;

    public Person (String name, String age, String height) {
    this.name = name;
    this.age = age;
    this.height = height;
    }

    public String get (String field) throws NoSuchFieldError {
    switch (field) {
    case "name": return name;
    case "age": return age;
    case "height": return height;
    default: throw new NoSuchFieldError(); // If the field inserted does not exist, it will show up an error
    }
    }

    public void set (String field, String value) throws NoSuchFieldError {
    switch (field) {
    // You will be able to set a regular expression for each field
    case "name": name = Data.regex("[.]", value); // Any character (do not validate real names)
    case "age": age = Data.regex("[0-9]", value); // A digit
    case "height": height = Data.regex("[0-9]]", value); // A digit
    default: throw new NoSuchFieldError();
    }
    }
    }

    /*
    e.g.:
    Person person = new Person();
    person.set("name", "Ruan Petterson");
    person.set("age", "100");
    person.set("height", "200");
    System.out.print(
    String.format(
    "I am %s. \n
    I am %s years old. \n
    My height is %s centimeters.",
    person.get("name"), person.get("age"), person.get("height")
    )
    );

    It will return:
    I am Ruan Petterson.
    I am 100 years old.
    My height is 200 centimeters.
    */
    [/code]

  43. Ruan Petterson says:

    Look at my way to do that:

    models/Person.java

    package models;

    public class Person {
    private String name;
    private String age;
    private String height;

    public Person () {
    }

    public Person (String name, String age, String height) {
    this.name = name;
    this.age = age;
    this.height = height;
    }

    public String get () {
    return String.format("%s, %s, %s", name, age, height);
    }

    public String get (String field) throws NoSuchFieldException {
    switch (field) {
    default:
    throw new NoSuchFieldException(
    String.format("NoSuchFieldException: \"%s\" is an invalid field name", field)
    );
    case "name": return name;
    case "age": return age;
    case "height": return height;
    }
    }

    public void set (String field, String value) throws NoSuchFieldException {
    switch (field) {
    default:
    throw new NoSuchFieldException(
    String.format("NoSuchFieldException: \"%s\" is an invalid field name", field)
    );
    case "name": name = Data.regex(".+", value); break;
    case "age": age = Data.regex("[0-9]+", value); break;
    case "height": height = Data.regex("[0-9]+", value); break;
    }
    }
    }

    models/Data.java
    [code]
    package models;

    public class Data {
    public static String regex (String regex, String input) {
    if (input.matches(regex)) {
    return input;
    } else {
    throw new IllegalArgumentException(
    String.format(
    "PatternInvalidException: \"%s\" is not valid value to \"%s\"",
    input, regex
    )
    );
    }
    }
    }
    [/code]

    testproject/TestProject.java
    [code]
    package testproject;

    import models.Person;

    public class TestProject {
    public static void main (String args[]) {
    try {
    Person person = new Person();
    person.set("name", "Ruan Petterson");
    person.set("age", "91");
    person.set("height", "271");
    System.out.println(
    String.format(
    "Name: %s \n" +
    "Age: %s years old \n" +
    "Height: %s centimeters",
    person.get("name"),
    person.get("age"),
    person.get("height")
    )
    );
    } catch (NoSuchFieldException | IllegalArgumentException e) {
    System.err.println(e.getMessage());
    }
    }
    }
    [/code]

    Result:
    [code]
    run:
    Name: Ruan Petterson
    Age: 91 years old
    Height: 271 centimeters
    BUILD SUCCESSFUL (total time: 0 seconds)
    [/code]

  44. Murali says:

    I have doubt on encapsulation. I have one class like below:

    public class Abc {

    private List list = new ArrayList();

    Abc(){
    list.add(“A”);
    list.add(“B”);
    list.add(“C”);
    list.add(“D”);
    list.add(“E”);
    }

    public List getList() {
    return list;
    }

    public void setList(List list) {
    this.list = list;
    }

    }

    and another class, which is accessing the list form the “Abc”, like below:

    public class Pqr {

    public static void main(String[] aa){
    Abc abc = new Abc();
    abc.getList().add(“F”);
    abc.getList().remove(“A”);
    Iterator it = abc.getList().iterator();
    while (it.hasNext()) {
    String str = (String) it.next();
    System.out.println(” : “+str);
    }
    }

    }

    Then, As all said “Encapsulation is the ability to package data, related behavior in an object bundle and control/restrict access to them (both data and function) from other objects.”

    But, my question is while accessing the private property using getters and we modifying the data from the another class. Is this all breaking the rule of encapsulation? Please explain>>

Comments are closed for "Java Encapsulation".