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

encapsulation  RSS feed

 
Kamila Bertran
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey. I thought that I'm grasping pretty well the idea of encapsulation but obviously I don't. So, would anyone care to explain?

I have this code (tests, tests):



What I don't get is why line 19 breaks encapsulation?
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe the reason is that you should return a copy of the List, not the List itself.  This is because someone could manipulate the List outside of the object.  An object needs to control its own data.
 
Campbell Ritchie
Marshal
Posts: 55687
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Let's enhance your class.Remember the + operator on Strings will cause the List's own toString method to be called, so you will get an obvious structure to your printout.Try that, and report back what happens.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!