Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

difference between Encapsulation & Abstraction  RSS feed

 
Harshada Deshmukh
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
can you please tell me difference bet Encapsulation & Abstraction by giving real-time examples?
Thank you in advance
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Abstraction simply means hiding the details of something. Encapsulation means binding the member variables and methods in a template called class. Now you have a encapsulated class. To achieve the abstraction you make the member variables private and allow accessibility only through methods (not directly) that are made public. The benefit of this abstraction is that, you are only providing accessibility of the members using methods that are the interface to the members variable of the class, so any changes in the internal of the class wont affect the world because the world is interacting with your class using the API.

public class DemoAccess {

private String str;

public void setStr(String str) {
this.str = str;
}
public void getStr() {
return str;
}
}

Now nobody outside the class can access the member variable str directly, using instance of the class. It has to use method setStr() to set the value and getStr() to get the value of the str.

Remember well encapsulated class encourages loose coupling.


cmbhatt
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I prefer to think of abstraction as ignoring details rather than hiding them. The List interface tells you a set of things an object can do, but encourages you to ignore how they might be done. The point of ignoring details is usually to focus on larger grained features.


The purpose of abstraction is not to be vague, but to create a new semantic level in which one can be absolutely precise. Edsger W. Dijkstra, "The Humble Programmer", October 1972

Abstraction is a means to ends, a basic tool of software engineering that we use to distill the essence of user needs toward writing less software to deliver the same capability. Larry Constantine


Encapsulation has about as many definitions as there are experts, authors, pundits, and Ranch posters. I first saw it connected to the OO idea of keeping data and behavior together, but I most often see it closely aligned with "information hiding" which has been in the vocabulary since the 1970s. "Private data and public behavior", or "tell, don't ask" might sum it up.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!