wood burning stoves 2.0*
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
Author

about setters and getters

Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 141
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.

Hunter.


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

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

Joined: Aug 16, 2005
Posts: 13875
    
  10

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 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: about setters and getters
 
Similar Threads
Super construction work
Problem formatting dates.
Recieving 'null' values from a jsp page in Struts2 Action
why getters/setters in java
how to pass Parameter in custom tag