Tuesday, January 4, 2011

Chapter 6: Object Oriented Concepts – Encapsulation

One of the key strengths of Java is that it is object oriented. In other words, everything in Java is an object. You might have heard me say this in the previous chapters and for sure I will say that at times in the future chapters as well because everything in Java is an object. There are a few important features/characteristics that Java exhibits by virtue of being object oriented. We will be covering them one by one in the following chapters.

Encapsulation:

Imagine that we both work for the same project and first you wrote the code for a class, and then I used your class in my program. Later on, you didn’t like the way the class behaved, because some of its instance variables were being set (by me from my code) to values you hadn’t anticipated. Their code brought out errors in your code. (Relax, I wont do that, dont worry.) Since, it is a Java program, so you should be able just to ship out a newer version of the class, which I could replace in my programs without changing any of my own code.

The above scenario highlights two of the promises or rather i should say benefits of Object Orientation (OO): flexibility and maintainability. But these benefits will not come automatically. You have to do something. You have to write your classes and code in a way that supports flexibility and maintainability. Just because Java supports OO concepts, it cannot write code for you. Can it?? For example, imagine if you made your class with public instance variables, and those other programmers were setting the instance variables directly, as the following code demonstrates:

public class BadExample {
public int size;
public int weight;
...
}
public class AnotherBadExample {
public static void main (String [] args) {
BadExample b = new BadExample ();
b.size = -5; // Legal but bad!!
}
}

Now go back the scenario we spoke about a paragraph ago. BadExample is your class and AnotherBadExample is my code. I have modified one of your variables in a way that it helps my code logic but that totally alters the way your class works. Now you are in trouble. How are you going to change your class in such a way that no one can alter your values directly (like what i have done in my code)? Your only choice is to write a method say setSize(int newVal) inside your class and then change the access modifier of the variable size to say, private. This will ensure that you handle instances when someone is trying to set a value to the size variable that you dont want and at the same time ensure that no one can access the size variable directly and mess with your code.

But, unfortunately, by doing that, you have broken my code. If I try to compile my AnotherBadExample class, i will get errors because the size variable is no longer visible for me.

How can we address this situation now? The best way is: not write such code where public variables are available for anyone and everyone to modify.


The ability to make changes in your code without breaking the code of all others who use your code is a key benefit of encapsulation. You should always hide implementation details. To elaborate, you must always have your variables as private and then have a set of public methods that others can use to access your variables. Since the methods are public anyone can access them, but since they are in your class you can ensure that the code works the way that is best for you. So in a situation that you want to alter your code, all you have to do is modify your methods. No one gets hurt because i am just using your method names in my code and the code inside your method doesnt bother me much.

If you want maintainability, flexibility, and extensibility (and I guess, you do), your design must include encapsulation. How do you do that?
• Keep instance variables protected (with an access modifier, mostly private).
• Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable.
• For the methods, use the JavaBeans naming convention of set and get.

We call the access methods getters and setters although some prefer the fancier terms accessors and mutators. (Personally, I will be using the terms getters and setters) Regardless of what you want to call them, they’re methods that other programmers must go through in order to access your instance variables. They look simple, and you’ve probably been using them forever if you have been writing java code:

public class GoodExample {
// protect the instance variable only an instance of your class can access it
private int size;
// Provide public getters and setters
public int getSize() {
return size;
}
public void setSize(int newSize) {
size = newSize;
}
}

You are now probably mumbling, what benefit is it to have methods that do nothing and just set or get values. I would rather have a public variable. If you did that go to the first paragraph under Encapsulation and re-read the whole thing. And if you did not do that but are asking me, where is the validation code that we are supposed to have in the setSize() method to ensure no one modifies it to invalid values, my friend this is just an example class. I leave you to ponder about how the implementation needs to be. Atleast you wont end up on the receiving side of unexpected shocks because of someone like me coding along with you or worse !!!

Tip: In the exam watch out for code that appears to be asking about the behavior of a method when the problem is actually lack of encapsulation. Check out the below example:
class Test {
public int left = 9;
public int right = 3;
public void setLeft(int leftNum) {
left = leftNum;
right = leftNum/3;
}
// lots of complex test code here
}

Now let us say I ask you this question: Will the value of the variable right always be 1/3rd of the value in left? It sure looks that way doesnt it? And if you said Yes, the answer is No. See these variables they are public and they are not encapsulated like the example just a paragraph above. So a novice programmer like me could always set the value directly inside my code to spoil the party.

You must be cautious in order to spot such questions that are fairly easy and straightforward but confusing if you are in a hurry to finish the question.

Previous Chapter: Self Test - Chapters 1 to 5

Next Chapter: Chapter 7: Object Oriented Concepts - Inheritance

6 comments:

  1. Thanks for your comment on my post What is Encapsulation in Java design pattern I see you have also covered the topic well.keep it up.

    ReplyDelete
  2. Great walk-through!!! but what is the difference between information-hiding and true encapsulation..

    ReplyDelete
    Replies
    1. They are not two totally distinct topics that you can separate. However, true encapsulation is the ability to make changes to your code without affecting all other code that is written by your colleagues. Whereas information hiding means - none of your data is visible to people who arent supposed to see it.

      Delete
  3. Good work Anand,
    It's a simple and easy explaination about Encapsulation..
    Thanks

    ReplyDelete
  4. nicely explained in simple easy to undrstand language....ws of grt help.
    thanx
    :)

    ReplyDelete

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers