6

I know my question will be nominated to be closed immediately upon publishing, but let me tell you that I had been searching the site for a clear cut difference in terms of an example, in Java. Please don't be in a hurry to close the question.

I've written the following:

public class Bank {
public String name="XXX Bank";
private int noOfCust;

public int getNoOfCust() {
 return getNoOfCusts() + 2;
}
public void setNoOfCust(int noOfCust) {
if(noOfCust > 0)
{
this.noOfCust = noOfCust;
}
}

private int getNoOfCusts()
{
noOfCust = 100;
return noOfCust;
}
}

Here, 'noOfCust is the data being hidden'. I am not exposing the implementation part by introducing private getNoOfCusts(). So I believe this is encapsulation, because I have bundled all the details in a class and have hidden the data too.

Question 1: If this strong encapsulation ? If not, how could I improve it to be strongly encapsulated?

Question 2: Abstraction means complete hiding of the implementation. So what I've done above is abstraction?

I've posted this question out of frustration because I had given the above explanation to an interviewer, who told me, this is not the correct meaning.

P.S: Please answer in terms of above example. I don't want real time examples or assumptions.

Anuj Balan
  • 7,629
  • 23
  • 58
  • 92
  • 2
    Why do you have two getters for the number of customers? Why does one of them *change* the value? – Thilo Aug 29 '12 at 06:35
  • It is just to specify that I can implement any logic I want in the private method I had written. In fact, there is no need, but I put that just to specify, logic can be changed later. – Anuj Balan Aug 29 '12 at 06:37
  • Maybe this helps: http://stackoverflow.com/questions/742341/difference-between-abstraction-and-encapsulation?rq=1 – Thilo Aug 29 '12 at 06:37
  • D@Nandkumar: Forget the code. I had written it just now in order to ask the question. I know it can be improved. I need clear cut difference between the concepts – Anuj Balan Aug 29 '12 at 06:38
  • I need answers in terms of the example given. I've almost gone through all the questions on encapsulation and abstraction from stackoverflow. – Anuj Balan Aug 29 '12 at 06:38
  • 1
    Is a dup: http://stackoverflow.com/questions/742341/difference-between-abstraction-and-encapsulation?lq=1 – imulsion Aug 29 '12 at 06:39
  • @Thilo: Can you please explain me the exact difference with the help of the program I had posted. I need it desperately. I do want to know why I was proved wrong by the interviewer, and I know you can help me on this. – Anuj Balan Aug 29 '12 at 06:41
  • I do not even expect/want +1 for this question, all I need is the exact difference. – Anuj Balan Aug 29 '12 at 06:42

5 Answers5

12

Choosing necessary properties and hiding unwanted details is Abstraction. For e.g. Consider Person. Person has eyes, eyeColor, skinColor properties. But if he goes to Bank, then Bank does his Abstraction and does not consider these Person's properties but it selects name, address, phone_number. This is Abstraction. You misunderstood it.

Encapsulation simply means binding object state(properties) and behavior(methods) together. If you are creating class, you are doing encapsulation.

From wiki : In object-oriented programming languages such as C++, Object Pascal, or Java, the concept of abstraction has itself become a declarative statement - using the keywords virtual (in C++) or abstract (in Java). After such a declaration, it is the responsibility of the programmer to implement a class to instantiate the object of the declaration.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
  • So usage of class fulfills encapsulation and usage of private methods(hiding implementation) fulfills abstraction ? – Anuj Balan Aug 29 '12 at 06:46
  • Wanted an explanation with ref to the example I'd asked. Dint want any real time examples. Moreover, you said hiding unwanted details is abstraction. But comments from others make me feel that abstraction is something that makes a general abstract methods, left for specific implementations. – Anuj Balan Aug 29 '12 at 08:20
  • Make methods and classes abstract. Create interface which you will expose it. edited an answer, hope it helps you. – Nandkumar Tekale Aug 29 '12 at 08:23
  • Does abstraction mean usage of abstract classes in java ? – Anuj Balan Aug 29 '12 at 08:28
  • IMO it depends, at design level abstraction and at coding level abstraction. `Design level abstraction : choosing necessary Object properties` and `coding level abstraction : usage of abstract classes and interfaces whenever necessary`. – Nandkumar Tekale Aug 29 '12 at 08:31
  • Ok. So would you tell if someone asks what Encapsulation and Abstraction are ? In your own words ? – Anuj Balan Aug 29 '12 at 08:40
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/15943/discussion-between-nandkumar-and-anuj-balan) – Nandkumar Tekale Aug 29 '12 at 08:41
3
  • The basic idea behind encapsulation is to hide the internal representation of an object from view outside of the class's definition. This is generally done to protect the internals of a class and provide a systematic way to access them.

  • Also, the idea behind having getter/setter combo is to provide a controlled way of accessing the properties of that class. So, for each private property of a class, you would would have public setter() and getter() method.

Taking these two into account, you can very well see why there's a problem with your code in terms of encapsulation. A skeleton class having this concept implemented might be as follows:

public class Bank{
    private int noOfCustomers;
    private String name;


    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getNoOfCustomers(){
        return this.noOfCustomers;
    }

    public void setNoOfCustomers(int noOfCustomers){
        this.noOfCustomers = noOfCustomers;
    }

    /**
    * This method is to illustrate that it is perfectly valid to have
    * multiple types of setter methods
    */
    public void setNoOfCustomers(String noOfCustomers){
        try{
            this.noOfCustomers = Integer.parseInt(noOfCustomers);
        }catch(Exception exe){
            //Handle exceptions
        }
    }
}

Regarding abstraction: You can think of it as an idea of presenting something in a simplified way, which is either easily comprehensible in terms of usage or more pertinent to the situation. Taking your example, you can think of Bank as an abstraction that can both represent a Federal Bank or a State Member Bank or anything for that matter. You would basically derive specific classes for each of those representations, taking Bank as the parent.

I think you can get a better picture of abstraction if you study what File represents in Java. File in itself is an abstract representation of file and directory pathnames. However, if you study the source codes, you would find that it contains several properties that are private to its design.

Encapsulation, as such can be thought as how well you protect your properties from misuse and abstraction, as such can be thought of how much simplification are you providing to the external user.

Sujay
  • 6,753
  • 2
  • 30
  • 49
  • Firs thing, the impl'n I had done in the code is fine for encapsulation? Secondly, how does abstraction differ from encapsulation. Can you explain by taking above example ? – Anuj Balan Aug 29 '12 at 06:50
2

Encapsulation: Okay, maybe. You have a very weird implementation, and the caller does not get to see it.

Abstraction: There we need to know what you are actually trying to do. The current interface looks like getter/setter of an integer value. That is not very abstract (and the implementation does not work like that, it does something else). For an abstraction the operation performed (or the object involved) needs to capture something that is not just divorced from the concrete implementation, but also applicable to a wider range of things (that are different, but still similar in that they can be made to belong under the same "abstraction"). Your example is probably just to small for this.

To try to build on the example, maybe you have a piece of code that categorizes businesses by their size. There would be the abstraction of "business" with properties such as number of customers, number of employees, etc. Code using this abstraction would work equally well with banks, pharmacies and grocery stores.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • So when someone says how do you achieve encapsulation in java, it is apt to say 'Class (Binding all info)','usage of private varb's(data hiding and implementaion)' ? – Anuj Balan Aug 29 '12 at 06:54
  • As a first approximation, yes. I personally would not say that simple beans with getters and setters and no logic in them are great examples of encapsulation. They are more like a fancy struct. – Thilo Aug 29 '12 at 06:55
  • Based on explanation given, abstraction would thus mean throwing out a generalized methods which will give others no idea on how it is going to be implemented, and it can be implemented by other classes with their own specifics ? – Anuj Balan Aug 29 '12 at 06:57
  • Can you please give an ex of good encapsulation other than usage of get/set. – Anuj Balan Aug 29 '12 at 06:58
  • I think java.lang.String is a good encapsulation. It is using a UTF-16 encoded array to hold the data (but you don't need to know that), it can convert between various binary encodings making sure that it really holds character data, it can do all sorts of functions for character data, and the encapsulation allows for a guarantee of immutability. – Thilo Aug 29 '12 at 07:06
  • And the matching abstraction would be the CharSequence interface. – Thilo Aug 29 '12 at 07:07
  • Ok. Can you finally give a line which describes what Encapsulation and Abstratcion is, in your own words ? – Anuj Balan Aug 29 '12 at 08:12
0

I believe you might be misunderstanding encapsulation and abstraction.

Encapsulation is more clearly explained in terms of a black box. The internals can change whenever necessary, but the public interface remains the same. With that said, your code is partially encapsulated, as you have a private int with a public getter and setter (and a private getter, which I see no purpose in, but that's up to you). However, String name is public and has no getter or setter; it appears you intend it to be a constant, in which case it should be declared as public, static, and final.

Abstraction is the concept of simplifying one idea to a more general, overhead idea. In Java, a class can be made abstract by providing an implementation which provides a general idea but lacks specifics, and it cannot be instantiated. This is achieved through the abstract modifier, which when modifying a class, denotes that the abstract class cannot be instantiated; when modifying a method (which must be in an abstract class), the modifier denotes that the abstract method must be defined in any subclass implementation.

Example of abstraction in Java, where abstraction dictates that Baseball is a Ball:

public abstract class Ball {
    // this class cannot be instantiated
    public abstract double getRadius();

    public double getVolume() {
        return (4.0 / 3) * Math.PI * Math.pow(getRadius(), 3);
    }
}

public class Baseball extends Ball {
    // this class can be instantiated
    @Override
    public double getRadius() {
        return 3.0;
    }
}
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • I had getters and setters for name but dint want to fill the page with 4 extra lines. So you say encapsulation is expose public methods but the logic can be changed anytime and is hidden – Anuj Balan Aug 29 '12 at 06:44
  • @Thilo I have rewritten my explanation of abstraction (with a focus on its use in Java) and provided an example. – FThompson Aug 29 '12 at 06:55
-1

Encapsulation in java takes place automatically through objects and methods. You do not need to take care of that . However if you want , you may use different means of concealment to increase your complexity. So, others will be unable to decipher your code. You may use recursive functions and complicated methods and add unnecessary codes. Strong Encapsulation !!

Arghya Chakraborty
  • 433
  • 1
  • 3
  • 12