aspose file tools*
The moose likes Beginning Java and the fly likes Encapsulation... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Encapsulation..." Watch "Encapsulation..." New topic
Author

Encapsulation...

Dan Silva
Ranch Hand

Joined: Sep 05, 2007
Posts: 86
Hi,
I really don't understand what the benefits of "encapsulation" are. What's the difference between a getter/setter method or just accessing the instance variable directly? What is the benefit when the end result is the exact same thing? Thanks.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

First, with getters and setters you have control over the values you allow.
Suppose you have a field called size. Now logic dictates that a size should not be negative. With a setter, you can prevent any negative values.

Second, consider this example:

Now you've been working with this code for quite a while now, but all of a sudden an int is not good enough anymore - you need a long:

If you had allowed direct access, anytime someone assigned the value of "size" to an integer, it would fail after the changes. With the getters and setters, it will still return an int, even though it is in fact a long.

All you need to remember is not to change any public method, or you will still break other code.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Petrus Pelser
Ranch Hand

Joined: Feb 20, 2006
Posts: 132
Most importantly it allows for validation. You can check the format, check for null values, etc. before assigning the value.
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

Let me try to explain you with a common life example that my senior told me when i asked him the same question :

suppose we have one room contain one cake, I am an intruder who wants to eat that cake...Now i can go and eat that cake..result..no cake for others..!!!

Now if we hire some guard for this room..!! this situation can be avoided..now suppose we have two guard..! getter and setter..!!! getter guy can make an exact duplicate of the cake..and give us that..!!! so we got the cake and one cake is also available in the room for others to eat..now suppose we find that in the duplicate cake sugar is bit less..!! so we can sugar to the cake and ask the setter guy to replace the original cake with our cake..!!! so that other won't have any problem..!!

Now suppose if some other guy get duplicate cake..!! mix some poison...and ask the setter to replace the cake..!!!
Oh My God..!!!
In this case we can ask the setter to do some testing on the cake before replacing..!!

I hope this will clear you concept of encapsulation..!!


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11477
    
  16

here's another example...

suppose you have a Person class. coders will want to know the age of the person. So, you write the person class to have an int age.

Now...

Option 1: Let users access the variable directly.

Option 2: Provide a getter method

Assume a year goes by. Lots of code has been written. You now realize that using an int is a bad way to store the age. it would be better to store the person's birthday, and calculate the age as needed. You want to re-write your person object to no longer store an int age, but a birth date. Users will call a method to get the actual age.

If you went with option 1, you're in for a world of hurt. ALL the code that uses the Person class has to be reviewed, edited, re-compiled, tested, fixed, distributed... and let's not forget about the fact that different customers will be on different versions of your software, and some may not upgrade for years...

Now, assume you went with option 2. the customer has always been calling a getAge() method. will they care (or even KNOW) if you change your method from
return age;
to


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Dan Silva
Ranch Hand

Joined: Sep 05, 2007
Posts: 86
Thanks!! These examples make a lot of sense!
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3355

One another pretty good example is, you have a Person object and whose size object is what you are trying to access or set.

Before the setters/getters were in picture or came into existence, the variables were declared public and given outside access without any harms.

In that case,



Just to have a better control on this value being accessed, there came a rescue in the form of Getters and Setters. As the name indicates, Getter is used to get/obtain a value and Setter is to set a value back. They are also called as Accessor and Mutators.

What if you allowed the access through a method and NOT directly? For which you need to have two things.

  • First "protect" your variable from outside access. Means, declare them to be of private.
  • Then provide getter and setter for your private variable. As the variable is pricate, the getter and setters should be public.



  • Following the same, the code will initially look like



    But had you been exposing your code through this way, it would be very easy in a later point when you realize that setting a negative value is a sin! you should NOT allow that!!, you have an easy way to get rid of it.

    Just modify/update the setter method as below



    This way, you really don't break the existing code. As such the users would still continue using your setAge() method to set an age.

    Here dealing with the invalid values and the condition to confirm the same may definitely based on the user and requirement. You can either set a default value or throw an exception or just let the user know about invalid value and continue the program normally.


    Hope this helps
    [ January 20, 2008: Message edited by: Raghavan Muthu ]

    Everything has got its own deadline including one's EGO!
    [CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    More generally speaking, encapsulation reduces coupling between classes, allowing it to make changes to classes without having to change its clients. This makes maintenance and extension of a software system much easier and less costly.

    Remember that for most systems, much more effort is put into maintenance than into initial development, so proper management of code dependencies pays manyfold.
    [ January 23, 2008: Message edited by: Ilja Preuss ]

    The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
    Raghavan Muthu
    Ranch Hand

    Joined: Apr 20, 2006
    Posts: 3355

    That's very true Ilja. Good and precise summary as well
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Encapsulation...