Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

oop concept

 
prakash pawar
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

can any one expain the Encapsulation with example

Thanks in advance.
 
W Pearce
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The big concept behind it is that you don't want your member variables being able to be manipulated outside of their own class. For example, if you have an int called height in a Bacon class, you don't want any code to be able to make an instance of that class and set height directly:



Instead, you want to have your instance variables wrapped in getter and setter methods, so you can perform validation on them when something is passing them a variable. So for the example above, we would do something like:

And these would be called from your code like this:
 
Anupam Jain
Ranch Hand
Posts: 61
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
W Pearce wrote:The big concept behind it is that you don't want your member variables being able to be manipulated outside of their own class. For example, if you have an int called height in a Bacon class, you don't want any code to be able to make an instance of that class and set height directly:



Instead, you want to have your instance variables wrapped in getter and setter methods, so you can perform validation on them when something is passing them a variable. So for the example above, we would do something like:

And these would be called from your code like this:



That's a good explanation... but I have something to ask....
with this explanation there doesn't seem to be any difference between "Encapsulation" and "Abstraction".

So far, I've been thinking that Encapsulation is all about just putting the things together... while...

Abstraction concerns the usability of the members....

so by that meaning.... the above thing is "abstraction"...
Please explain if I am wrong.... ???
 
salvin francis
Bartender
Posts: 1274
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you might want to look at this:
http://www.coderanch.com/t/383749/Java-General/java/difference-between-abstraction-encapsulation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic