File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about setters and getters

 
Raj chiru
Ranch Hand
Posts: 142
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q: Why setters and getters are required? Why cant an instance variable directly referenced?
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance variables are by convention set to Private, which enables them not to be directly changed by other classes or outside sources.

Public getter and setter methods allow you to return and change the values of the instance variables in a controlled way.

Hunter.
 
Raj chiru
Ranch Hand
Posts: 142
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Hunter
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason why it's considered bad to expose the member variables directly by making them public is because of the concepts of encapsulation and low coupling.

If you would directly make the member variables of a class visible to the outside world, you're really showing the inside of the class to the outside world. If you need to change the implementation of the class later, and you need to change the member variables, it will be much harder to do this if the rest of your program is accessing those member variables directly - it means that your changes go through your whole program, instead of just in the class you need to change. If a variable would only be visible through getter and setter methods, you could change the class and change the getter and setter method so that the class would for the outside world still look the same (i.e. you only have to change one class).
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic