1 2 Previous Next 16 Replies Latest reply: Aug 6, 2011 4:23 AM by 796440 RSS

    Abstraction and Encapsulation i.e basic oops concepts gist and their unders

    866541
      I have gone to many sites and everywhere got some difference in defintion of abstraction and encapsulation.
      Below i tried to summarize the findings of both and have some questions which are inline with understanding.

      Encapsulation:-
      Hiding internal state and requiring all interaction to be performed through an object's methods is known
      as data encapsulation — a fundamental principle of object-oriented programming.

      Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.


      Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
      methods. Is it not the violation of encapsulation? What advantage it provides exposing the internal state thru methods
      (like getter and setter) but not declaring stae with public modifier.?

      Question2:- If class does not have any state variable and has some just simple methods printing hello world.
      Can we still say it is encapsulation?


      Abstraction:-Abstraction in Java allows the user to hide non-essential details relevant to user.

      Question1:- so we can say Encapsulation is also a feature of abstraction because in ecapsulation also we hide data(state) of object. Right?

      Question2:-Say a class has 10 methods . Out of these 10 , only two are exposed for outside world with public modifier.Can we say this is the example of abstraction?

      Question3:- Can we say interface/abstract class are the baset examples of abstraction as they just expose the masic details i.e signature of method to outside world?
        • 1. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
          EJP
          Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
          methods. Is it not the violation of encapsulation? What advantage it provides exposing the internal state thru methods
          (like getter and setter) but not declaring stae with public modifier?
          Good question. I think the manic proliferation of getters and setters everywhere has more to do with debugging practicalities rather than formal principles. However I worked on a system some 22 years ago that had zillions of items of global data: the new subsystem I wrote had none atall, and it was regarded as a considerable improvement in engineering practice which they immediately copied for all new code. I would too. But I think it's more about engineering than about formal principles.
          Question2:- If class does not have any state variable and has some just simple methods printing hello world.
          Can we still say it is encapsulation?
          No because there is nothing to encapsulate, unless you want to think that it is encapsulating the fact that it has nothing to encapsulate.
          Abstraction:-Abstraction in Java allows the user to hide non-essential details relevant to user.
          No it doesn't. It allows you to define a method signature without requiring that an implementation be present at the point of definition. The specific type/class/abstraction being defined at that point has a specification but no actual behaviour.
          Question1:- so we can say Encapsulation is also a feature of abstraction because in ecapsulation also we hide data(state) of object. Right?
          Not relevant because of the above.
          Question2:-Say a class has 10 methods . Out of these 10 , only two are exposed for outside world with public modifier.Can we say this is the example of abstraction?
          No.
          Question3:- Can we say interface/abstract class are the best examples of abstraction as they just expose the basic details i.e signature of method to outside world?
          They are the only examples of abstraction as far as I can see.
          • 2. Re:  Encapsulation is the technique
            BIJ001
            Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods.
            It is not a very fortunate wording. Encapsulation is not a technique, it is a principle. Besides, technically seen, encapsulation is more than just that.
            There are other non-public access modifiers than just private, making their contribution to the levels of encapsulation.

            The getters and setters provide access to the fields if it is appropriate for the given class.
            You don't have to write getters and setters for every field - on the contrary.
            Private fields pertinent only to the internalia of the implementation don't need getters and setters.
            Using getters and setters (where appropriate) leaves the liberty for the implementor to change the internal representation.

            I am sure there are tons of discussions about this.
            • 3. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
              YoungWinston
              JavaFunda wrote:
              Question1:- ...What advantage it provides exposing the internal state thru methods (like getter and setter) but not declaring stae with public modifier.?...
              One common use is to ensure consistency. For example, if your application has a Customer class that includes a Date field for Date of Birth, a setter could ensure that it's not more than 125 years ago (I believe the oldest authenticated person so far was 122 when she died); a CreditCardNumber setter might perform the mod-10 check digit calculation to verify a supplied number... And there are many other examples.

              Now, whether or not you make those setters public is an entirely different matter. Like EJP, I don't like to see tons of getters and setters; it smacks too much of "Bean-ish" design to me. My general rule of thumb is to avoid public setters if I possibly can, and to provide getters only for items that are useful to a client.

              That doesn't mean to say that you can't allow modification, but to my mind it's much better if it's done as part of recognized behaviour. For example, using the Customer class above, there may be reasons why someone might change their name, but rather than simply providing name setters I'd probably try to come up with a method like 'marriageChange()' or 'deedPollChange()' that encompasses the whole activity (which may involve verifying documents), rather than forcing clients to change each little piece of information themselves.

              I found [url http://martinfowler.com/bliki/FluentInterface.html]this article on "fluent interfaces" very interesting. You may disagree with it, or find its suggestions over the top, but knowing about different approaches is never a bad thing. Another good one, also related to your questions, is [url http://pragprog.com/articles/tell-dont-ask]this one.

              Winston

              Edited by: YoungWinston on Jul 29, 2011 3:03 PM
              • 4. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                836548
                JavaFunda wrote:

                Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
                methods. Is it not the violation of encapsulation? What advantage it provides exposing the internal state thru methods
                (like getter and setter) but not declaring stae with public modifier.?
                No, by doing so you makes sure, the state can be changed only by using these methods.

                The good example is singleton class

                You make the constructor private and returns the instance using static public method.
                • 5. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                  jschellSomeoneStoleMyAlias
                  JavaFunda wrote:
                  I have gone to many sites and everywhere got some difference in defintion of abstraction and encapsulation.
                  Below i tried to summarize the findings of both and have some questions which are inline with understanding.

                  Encapsulation:-
                  Hiding internal state and requiring all interaction to be performed through an object's methods is known
                  as data encapsulation — a fundamental principle of object-oriented programming.

                  Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.


                  Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
                  methods. Is it not the violation of encapsulation?
                  Yes.

                  Since you are in fact exposing the 'data' their can be no question that it violates encapsulation.

                  In terms of methods the advantage is that it you want to change the data later that you then have an avenue of doing so as you can then map to the older data format. That however doesn't alter the fact that initially you did in fact expose the data.
                  What advantage it provides exposing the internal state thru methods
                  (like getter and setter) but not declaring stae with public modifier.?
                  In practical programming - not much.

                  There are two cases.
                  1. Your design is broken. Data is exposed all over the place because your objects are not really objects.
                  2. Your design is not broken. So data exposure, regardless of idiom, is limited.

                  For case 1 it is broken from the beginning so it doesn't matter what happens later.

                  For case 2 most of the time in the cases where you need to change class X in such a way that you need to change the exposed data in a significant way then you are going to be fundamentally changing the intent of the class anyways. So changes would have a cascade effect which require other changes.

                  So using the classic 'Shape' example where you start out with a Circle and expose origin (X and Y coordinates and circumference) in the second case it will turn out that you should have been using a Square rather than a Circle.
                  Question2:- If class does not have any state variable and has some just simple methods printing hello world.
                  Can we still say it is encapsulation?
                  An Object must have data and behavior.

                  If either is missing it is not an object.

                  Doesn't mean that programmatically you might not use 'class' to encapsulate behavior (such as static methods) nor that a 'class' might not encapsulate data (with no non-trivial functionality.) But rather that in those cases they are not Objects.

                  >
                  Abstraction:-Abstraction in Java allows the user to hide non-essential details relevant to user.

                  Question1:- so we can say Encapsulation is also a feature of abstraction because in ecapsulation also we hide data(state) of object. Right?
                  I would say yes.

                  >
                  Question2:-Say a class has 10 methods . Out of these 10 , only two are exposed for outside world with public modifier.Can we say this is the example of abstraction?
                  Err...not sure about that.

                  Methods in that case are used to implement the class in state that makes it more maintainable (hopefully.) The private methods limit the access so they cannot be used in ways not intended. But private methods by themselves are not required to provide abstraction. If the language didn't allow for private methods I could just document that they should not be used. That would still maintain the intent of abstraction it just would not enforce it.
                  Question3:- Can we say interface/abstract class are the baset examples of abstraction as they just expose the masic details i.e signature of method to outside world?
                  As expressed - no.

                  You use interface/abstract class to specify a type. That specification however is not a definition of abstraction. A class without those provide abstraction as well. So those are a tool to provide a better level of control in implementation for a common type of abstracted implementation.
                  • 6. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                    866541
                    What if ia object has only instance variable not any method(not even getter and setters). Can we call it encapsulation?
                    • 7. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                      YoungWinston
                      JavaFunda wrote:
                      What if ia object has only instance variable not any method(not even getter and setters). Can we call it encapsulation?
                      Well, if the instance variable is private, I'd call it useless.

                      Winston
                      • 8. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                        796440
                        jschell wrote:
                        JavaFunda wrote:
                        I have gone to many sites and everywhere got some difference in defintion of abstraction and encapsulation.
                        Below i tried to summarize the findings of both and have some questions which are inline with understanding.

                        Encapsulation:-
                        Hiding internal state and requiring all interaction to be performed through an object's methods is known
                        as data encapsulation — a fundamental principle of object-oriented programming.

                        Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.


                        Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
                        methods. Is it not the violation of encapsulation?
                        Yes.

                        Since you are in fact exposing the 'data' their can be no question that it violates encapsulation.
                        So methods that directly set or return the value of a member variable violate encapsulation, but those that indirectly set such a value or return some calculation based on it do not?

                        What about this?
                        public class Foo {
                          private int bar;
                        
                          public void setBaz(int baz) { bar = baz + 1; }
                          public int getBaz() { return baz - 1; }
                        }
                        An Object must have data and behavior.

                        If either is missing it is not an object.
                        I'll pretend for the moment that I agree with that. What counts as "behavior" for you? Do typical direct set/get count? If not, how much indirection is required between a method's name and parameters and the effect it has on an object's state for it to count as behavior, and how to you measure that indirection? Your statements above certainly suggest that you have a precise, iron-clad, unambiguously-and-objectively-covers-all-situations definition for "behavior."
                        • 9. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                          866541
                          Hi jverd whats your take on original post?
                          • 10. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                            796440
                            JavaFunda wrote:
                            Hi jverd whats your take on original post?
                            Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
                            methods. Is it not the violation of encapsulation? What advantage it provides exposing the internal state thru methods
                            (like getter and setter) but not declaring stae with public modifier.?
                            >

                            I don't think you can say whether an individual get/set "violates encapsulation" without more context. If you're just blindly providing direct get/set for every member variable, then it's likely you don't understand encapsulation. There's still some encapsulation there, however, because the caller can't directly see or modify the state.

                            Sure, a programmer familiar with coding conventions and possessing some common sense could infer that those get/set methods correspond directly to member variables of the same names, but so what? He still has to go through the methods to see or modify the state, and there could be other stuff going on there. The fact that going through the method makes it a black box to him is why I say there's some level of encapsulation. There's a continuum of how "direct" the access to the internal state is, and I don't think there's a clear delineation between "encapsulated" and "not encapsulated."

                            For example:

                            As direct as can be: setX() is simply this.x = x and getX() is simply return x.

                            Somewhat less direct: getFullName() returns firstname + " " + lastName. There's no member variable called "fullName", and the result is composed by operating on multiple pieces of the object's state.

                            Still less direct: ArrayList's toString() is "[", followed by the results of each of its elements' toString() methods, separated by commas, followed by "]"

                            Very indirect: Map.put(). We know that it modifies the state of the Map by adding the key/value pair we specify, and we can infer some things about how it's implemented based on the type of Map. But that abstraction is so far separated from the specific state that represents it, that we would probably say that there's a high level of encapsulation there.

                            And of course there are other scenarios in between these, and further toward the "encapsulated" end of the spectrum than the Map example. Where do you draw the line between "not encapsulated" and "encapsulated"?

                            I think a reasonable criterion to use is whether the exposed stated has been exposed because it's a natural part of the behavior of the class.

                            For instance, Colleciton.size(). It makes sense that as part of a Colleciton's behavior, you'd want it to be able to tell you how many items it holds. In an ArrayList, you would probably have a size variable that gets updated each time an element is added or removed. However, in a ConcurrentSkipListSet, there is no size variable. You have to traverse the Set and count the elements. So is size encapsulated here? Is it in one but not the other? Why? I would say it is in both cases, because part of the natural behavior of a Collection is to tell us its size, so the fact that in some collections that can be done simply be returning the value of a member variable doesn't "violate" encapsulation.

                            But, after having said all that, my real answer is: I don't care. The answer to "Do get/set violate encapsulation?" doesn't matter to me in the least in how I write my code.

                            >
                            Question2:- If class does not have any state variable and has some just simple methods printing hello world.
                            Can we still say it is encapsulation?
                            >

                            I would say no, since there's no state to be encapsulated. However, I supposed one could say that the behavior is encapsulated. It could be implemented any number of different ways, some of which would involve state and some wouldn't, and all we'd see is the public interface and the behavior it provides. I don't know that anybody actual does view it that way though.

                            And, again, this sort of nitpickery is not actually relevant to anything, IMHO.

                            >
                            Question1:- so we can say Encapsulation is also a feature of abstraction because in ecapsulation also we hide data(state) of object. Right?
                            >

                            More silly semantics. I wouldn't say that encapsulation is a "feature" of abstraction. I think the two often work together, and there's some overlap in their definitions, or at least in how they're realized in code. (Which can be seen in my long-winded answer to the first quetsion.)

                            >
                            Question2:-Say a class has 10 methods . Out of these 10 , only two are exposed for outside world with public modifier.Can we say this is the example of abstraction?
                            >

                            Don't know, don't care.

                            >
                            Question3:- Can we say interface/abstract class are the baset examples of abstraction as they just expose the masic details i.e signature of method to outside world?
                            >

                            No idea what you're saying here, but I expect my answer will again be: "don't know, don't care".

                            Edited by: jverd on Aug 3, 2011 10:22 AM

                            Edited by: jverd on Aug 3, 2011 10:22 AM
                            • 11. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                              DrClap
                              JavaFunda wrote:
                              Encapsulation:-
                              Hiding internal state and requiring all interaction to be performed through an object's methods is known
                              as data encapsulation — a fundamental principle of object-oriented programming.
                              Yes.
                              Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
                              No.

                              Or rather, that's a very naive way of looking at it. It makes the assumption that the "internal state" of an object simply consists of a set of fields, and that interacting with the object can be reduced to simply interacting with those fields, indirectly. That may be the case a lot of the time but it certainly isn't the only way to do encapsulation.

                              It might be the case that the internal state of an object is represented by some data on an LDAP server, and the methods of the object allow the user to manipulate that data in controlled ways, for example.
                              • 12. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                                jschellSomeoneStoleMyAlias
                                jverd wrote:
                                jschell wrote:
                                JavaFunda wrote:
                                I have gone to many sites and everywhere got some difference in defintion of abstraction and encapsulation.
                                Below i tried to summarize the findings of both and have some questions which are inline with understanding.

                                Encapsulation:-
                                Hiding internal state and requiring all interaction to be performed through an object's methods is known
                                as data encapsulation — a fundamental principle of object-oriented programming.

                                Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.


                                Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
                                methods. Is it not the violation of encapsulation?
                                Yes.

                                Since you are in fact exposing the 'data' their can be no question that it violates encapsulation.
                                So methods that directly set or return the value of a member variable violate encapsulation, but those that indirectly set such a value or return some calculation based on it do not?
                                The conceptual model is based on hiding the data of the object.

                                A set/get that is used to expose the data of the object exposes it.
                                A method that doesn't expose the data of the object doesn't expose anything.
                                I'll pretend for the moment that I agree with that. What counts as "behavior" for you?
                                Non-trivial behavior.
                                Do typical direct set/get count?
                                No.
                                If not, how much indirection is required between a method's name and parameters and the effect it has on an object's state for it to count as behavior, and how to you measure that indirection?
                                It has nothing do with indirection in terms of determining whether it is an actual object. It depends on the complexity represented by all behaviors of the object.
                                Your statements above certainly suggest that you have a precise, iron-clad, unambiguously-and-objectively-covers-all-situations definition for "behavior."
                                Pretty sure my statements do not in fact make that claim.
                                • 13. Re: Abstraction and Encapsulation i.e basic oops concepts gist and their unders
                                  796440
                                  jschell wrote:
                                  jverd wrote:
                                  jschell wrote:
                                  JavaFunda wrote:
                                  I have gone to many sites and everywhere got some difference in defintion of abstraction and encapsulation.
                                  Below i tried to summarize the findings of both and have some questions which are inline with understanding.

                                  Encapsulation:-
                                  Hiding internal state and requiring all interaction to be performed through an object's methods is known
                                  as data encapsulation — a fundamental principle of object-oriented programming.

                                  Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.


                                  Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
                                  methods. Is it not the violation of encapsulation?
                                  Yes.

                                  Since you are in fact exposing the 'data' their can be no question that it violates encapsulation.
                                  So methods that directly set or return the value of a member variable violate encapsulation, but those that indirectly set such a value or return some calculation based on it do not?
                                  The conceptual model is based on hiding the data of the object.

                                  A set/get that is used to expose the data of the object exposes it.
                                  A method that doesn't expose the data of the object doesn't expose anything.
                                  You say that as if it were a clear-cut, well-defined, yes/no proposition.
                                  I'll pretend for the moment that I agree with that. What counts as "behavior" for you?
                                  Non-trivial behavior.
                                  Ah, yes, another clear-cut, objective, binary value.
                                  Do typical direct set/get count?
                                  No.
                                  If not, how much indirection is required between a method's name and parameters and the effect it has on an object's state for it to count as behavior, and how to you measure that indirection?
                                  It has nothing do with indirection in terms of determining whether it is an actual object. It depends on the complexity represented by all behaviors of the object.
                                  So what value marks the complexity threshold, and how do you measure it?
                                  Your statements above certainly suggest that you have a precise, iron-clad, unambiguously-and-objectively-covers-all-situations definition for "behavior."
                                  Pretty sure my statements do not in fact make that claim.
                                  Ah, my mistake then, for taking your blunt, unqualified, unembellished statements as if you were stating a simple fact, rather than expressing a fuzzy, subjective gradation, which it is now clear is what you were doing. Thank you for clearing that up.
                                  1 2 Previous Next