Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By jim829

Thread: Understanding encapsulation and abstraction

  1. #1
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Understanding encapsulation and abstraction

    I know abstraction and encapsulation have been discussed many a times in many forums, but I am still not clear. I expect the experts here to pls help me out. Pls help me correct my understanding.

    Encapsulation is the concept by which we can combine data and method in a class. It is a protective layer(class) by which we dont allow access(or allow access in a specific format) so that the data and method of a class is not used/misused by someone.

    Abstraction is the concept by which we hide the essential features and expose the functionality. Don't know an example.

    1. Are the above statements defined by me correct?
    2. Can a class also serve as an example for abstraction?
    2.1 If not what can serve as a practical example of abstraction?
    2.1.1 An abstract class or interface can be seen as a example of abstraction?
    3. Are encapsulation and abstraction related concepts?
    3.1 To me it looks like they are concepts which are subtly different. Am I correct or wrong?

  2. #2
    BinaryDigit09 is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Re: Understanding encapsulation and abstraction

    Your definition of encapsulation is correct for the most part. As a very basic example, if you have a Person class and need to keep track of the person's name, proper encapsulation would be to do the obvious thing and put the variable for personName inside the Person class. Since the responsibility of the Person class is to hold data about a Person, proper encapsulation means you're letting it do its job instead of making someone else responsible for it.

    The definition of abstraction you have seems wierd to me. Abstraction is where you have common data/functionality in a more generic superclass. Usually the point is to keep from having to copy/paste the same boilerplate code into every subclass. If you need Employee and Candidate classes, they both have names (and probably phone #s, SSNs, etc.) so it makes sense to make them both extend Person (and add phone# and SSN fields to Person of course). Then the Person class is an abstract representation of some person, while Employee and Candidate are more specific types of Person.

    1. Are the above statements defined by me correct?

    See above.

    2. Can a class also serve as an example for abstraction?

    Yes, in fact that's often the case. Hopefully the way I described abstraction above, the answer is more clear now.

    2 .1 If not what can serve as a practical example of abstraction?

    The only other way I can think of is something like having a default method along with specific ones. As a rough example:

    Java Code:
    	public void doThing(Object object) {
    		doThingDefault(object);
    		if (object instanceof Integer) {
    			doThingInteger((Integer)object);
    		} else if (object instanceof String) {
    			doThingString((String)object);
    		}
    	}
    
    	private void doThingDefault(Object object) {}
    	private void doThingInteger(Integer integer) {}
    	private void doThingString(String string) {}
    The doThingDefault() method is effectively abstract, because it provides default behavior for the doThing() method before it moves on to specific work based on the argument.

    2.1.1 An abstract class or interface can be seen as a example of abstraction?

    An abstract class can definitely be seen as an example of abstraction. That's actually the whole point of abstract classes. They often have default behavior that calls their own abstract methods. When a class extends the abstract class, it's required to implement the abstract method(s). So when the default behavior from the superclass calls the abstract method, it actually calls the subclass's implementation of the method. So subclasses get default behavior from the superclass, but can be customized by overriding/implementing methods from the superclass.

    An interface can technically also be seen as an example of abstraction, but it's much less obvious IMO. The class that implements an interface is basically saying, "Here's what I can do for you." The code that uses the class doesn't have to know how it gets done, only that it will. For example, ArrayList and LinkedList both implement the List interface, so they both have methods like add(), get(), and remove(). But how they implement these methods is very different from each other, because the way they handle their internal lists is different. So that's one way that an interface can be an example of abstraction.

    3. Are encapsulation and abstraction related concepts?

    Not very much in my mind. Abstraction generally involves providing default fields and/or behavior in a class that's meant to be extended (or in the case of interfaces, requiring that default behavior be implemented). Encapsulation is about making objects reasonably self-sufficient. Here's a crude Parent class that encapsulates its own childCount variable and keeps it up-to-date:
    Java Code:
    class Parent {
    	
    	List<Child> children;
    	int childCount;
    	
    	public void add(Child child) {
    		children.add(child);
    		childCount++;
    	}
    	public void remove(Child child) {
    		children.remove(child);
    		childCount--;
    	}
    	public int getChildCount() {
    		return childCount;
    	}
    	
    }
    3.1 To me it looks like they are concepts which are subtly different. Am I correct or wrong?

    More than subtly, IMO. I hope that helps.
    Last edited by BinaryDigit09; 04-12-2014 at 05:14 PM.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,501
    Rep Power
    5

    Default Re: Understanding encapsulation and abstraction

    The concept of abstraction in Java or OOP in general is not related to abstract classes. Here is a discussion from the past on the topic.

    Abstraction and Encapsulation


    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  4. #4
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Understanding encapsulation and abstraction

    But my confusion is people say Encapsulation is a way of having variables and methods inside the class so that they can be accessed outside through a specific syntax and provides a protective layer. Then what is abstraction all about? Is the purpose of abstraction not data hiding? So, wheres the difference?

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,501
    Rep Power
    5

    Default Re: Understanding encapsulation and abstraction

    As I have stated before, but in different words, I tend to think of abstraction as the design part of
    a system and the encapsulation as the implementation of that abstraction.

    If I build some electronic gadget to do a function I only give access to the essential parts
    (perhaps probes in a multimeter). The user does not need to know or care about the internals.

    But during the build process I accidentally wire one probe up to house current. Now the device can
    be dangerous to the user and anything the user might test.

    So my design (the abstraction part) was right on. The encapsulation part (the enforcement of the abstraction) sucked.

    Similar in Java. If you return a reference from a method via a getter, you are doing something related to abstraction (you don't
    have a clue as to how the reference is stored in the class). If you return the actual reference and not a copy, your encapsulation
    is faulty (because now the user can change something internally via that reference that probably wasn't meant to be).

    Regards,
    Jim
    gimbal2 likes this.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,848
    Rep Power
    5

    Default Re: Understanding encapsulation and abstraction

    What Jim says. Here is a simple form of encapsulation.

    Java Code:
    public class Person {
      private String name;
    
      public Person(String name){
        this.name = name;
      }
    
      // example 1: no setter for name. You can't change the name of the person after its created. This is often mistakenly documented as being "the way" to do encapsulation.
      // that is only true in this case because name is a String and so is immutable
      public String getName(){
         return name;
      }
    }
    
    public class Receipt {
       private Person person;
    
       public Receipt(Person person){
         this.person = person;
       }
    
       // example 2, in my opinion the far more important example of encapsulation. Don't provide access to the internal Person reference
       public String getNameOnReceipt(){
          return person.getName();
       }
    }
    Now to show where it fails. Lets make Person so you can change the name.

    Java Code:
    public class Person {
      private String name;
    
      public Person(String name){
        this.name = name;
      }
    
      public String getName(){
         return name;
      }
    
      // nothing functionally wrong with this, names can change
      public void setName(String newName){
         this.name = newName;
      }
    }
    And now we're going to break encapsulation on the Receipt.

    Java Code:
    public class Receipt {
       private Person person;
    
       public Receipt(Person person){
         this.person = person;
       }
    
       public Person getRecipient(){
          return person;
       }
    }
    At first glance there is nothing wrong, there is no setPerson() method so we can't change the recipient, right? Wrong.

    Java Code:
    Receipt receipt = new Receipt(new Person("Suhaas"));
    
    // Oops. Should it be possible to change the name of a person through the receipt? I don't think so, in the real world the old name will be printed on that piece of paper.
    receipt.getPerson().setName("Trololol");
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Understanding encapsulation and abstraction

    Just a few examples about abstraction and encapsulation:
    Just take a car. It is something really complex. But the car offers simple to use interfaces. You can open the door without knowing much about the technology behind it. The implementation is hidden. When you start the motor, you do not need to know how it exactly works.
    And through common interfaces, you can drive all cars. So even that there are a lot of different vendors and technologies: through the abstraction you can drive cars.

    And it is the same in java:
    Complexities are hidden. A class encapsulated it. you do not even know the details.
    And through abstraction stuff can be used in the same way. So if you know "car", then you can use all special cars.

Similar Threads

  1. Abstraction and Encapsulation
    By suhaas.mohandos@gmail.com in forum New To Java
    Replies: 22
    Last Post: 08-27-2013, 02:29 PM
  2. Replies: 1
    Last Post: 09-05-2012, 05:36 AM
  3. Are abstraction and encapsulation concepts not in C?
    By hitesh_public in forum New To Java
    Replies: 1
    Last Post: 08-20-2010, 02:23 PM
  4. Abstraction
    By maya700 in forum New To Java
    Replies: 4
    Last Post: 07-04-2010, 06:26 PM
  5. Abstraction
    By anurag in forum New To Java
    Replies: 6
    Last Post: 05-15-2010, 06:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •