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.
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.