File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes about setters and getters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "about setters and getters" Watch "about setters and getters" New topic

about setters and getters

Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 142
Q: Why setters and getters are required? Why cant an instance variable directly referenced?
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

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.


"If the facts don't fit the theory, get new facts" --Albert Einstein
Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 142
Thank you Hunter
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

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).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
jQuery in Action, 3rd edition
subject: about setters and getters
jQuery in Action, 3rd edition