• Post Reply Bookmark Topic Watch Topic
  • New Topic

encapsulation  RSS feed

 
trinadh reddy
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have asked in one interview like this
class a
{
public int i;
}
is it encapsulated
i told that if the specifier is not public it is encapsulated
can you tell me the solution for this
 
David McCombs
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since the variable is public, it can be directly accessed from outside the class. Doesn't that violate the definition of encapsulation?

If it is private, it can't be directly accessed from outside the class. Doesn't that sound like it is encapsulated? Make i private and you have the solution, unless I totally misunderstand your question.

I have heard arguments that protected breaks encapsulation, which is true, but it still offers some encapsulation. Personally, I think that is just nitpicking.

default offers less data hiding then protected.
 
Nalaka Gamage
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class a
{
public int i;
}

Yes this violate encapsulation. You must make your member variables private and only use public accessor method to access them. Encapsulated version of the class should be as follows;


class a
{
private int i;
public int getI(){
return i;
}
public void setI(int i){
this.i = i;
}
}

Cheers,
JavaTouch
http://javatouch.googlepages.com
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!