wood burning stoves
The moose likes Beginning Java and the fly likes setter / getter: doesnt make sense Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "setter / getter: doesnt make sense" Watch "setter / getter: doesnt make sense" New topic

setter / getter: doesnt make sense

choubix alex

Joined: Dec 25, 2009
Posts: 22
hi there,

I've come to the point where, in the 2 books I am using right now, the authors are mentioning the getters and setters as a way to "enforce" control over the variables. It doesnt quite make sense to me... the couple of examples I foudn online do not make much sense either...

can someone shed some light on this for me please?

basically: why would I NOT want to interact directly with the variables I have created in a class? it seesm more "natural" to me to use them directly...

and : is the use of constructors and getters/setters mutually exclusive? (it seems quite difficult to me to combine both at the same time even though the purpose is different)

Marco Ehrentreich
best scout

Joined: Mar 07, 2007
Posts: 1294

Hi choubix,

basically there's nothing wrong with accessing public variables directly - as long as you only set and get values! If you need to do slightly more than just that or for example if you need synchronization for multithreaded apps you will have to use getter/setter methods. Another example are immutable data. If you directly access mutable member variables like a Date or any mutable collection you break encapsulation because all clients which hold a reference to it can manipulate the internal state of your object from outside the object.

In Java there's of course something special about getters/setters. It's part of the JavaBeans convention and used by many tools and frameworks to automatically identify properties of a class.

and : is the use of constructors and getters/setters mutually exclusive? (it seems quite difficult to me to combine both at the same time even though the purpose is different)

I'd say it's not mutually exclusive. But often you don't have all information available when you create an object so that you could pass in all needed values. And if you have more than a few members you want to set the signature of your constructors soon get very ugly. But it is always a trade-off to decide what to set in a constructor and what not.

Mark Judman

Joined: Oct 20, 2007
Posts: 14
If you have a public int instance variable "age" there's nothing to prevent someone or some other method in your application from setting the employee's age to 325 years old or to a negative value. With the use of a setter method you can build-in or enforce a restriction to reasonable values. The point is to make those instance variables private and give access only through the public (or protected or default) getter and setter methods. The getter method then, is necessary for one thing because the instance variable has been made private. Hope this helps.
W. Joe Smith
Ranch Hand

Joined: Feb 10, 2009
Posts: 710
The use of getters/setters is part of OO design. By having a setter/getter, you can set your instance variables to private, giving you more control over what the variables are set to. For instance, say you have an object Cat with a numberLegs variable. You wouldn't want someone to be able to say your Cat has -2 legs (if you have a picture of a cat with -2 legs, I would love to see it!). By requiring all calling code to use the setter, you can put a requirement that the numberLegs be greater than or equal to zero.

In summary, they allow you to have control over what values can be used in your instance variables, which can help prevent your program from crashing.

Constructors and getter/setters are not mutually exclusive. A constructor is used to perform anything that needs to be done each time an object of a specific type is created, which could be setting the default values of the instance variables. For my Cat example, my constructor would default numberLegs to 4, since that is a reasonably safe value to assign to that variable. I would then have a getter so other programs could pull that variable's value, and a setter in case the particular cat they are dealing with has more/less than 4 legs.

When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11882

I don't think books ever do a good job of explaining this.

Remember that in the 'real world', your often working on a team with dozens of developers. Each may have an idea how something should be used. Using getters and setters keeps people from clobering each other.

Suppose we have an object that stores the age of something as an int. I may need the age stored in years. You may need it stored in minutes. If everyone has direct access to the variables, you never know how anybody will store stuff.

If there are setters, I can enforce the age being in years. If you try and set the age in seconds, the code can reject an age of 525,600 minutes for a person. Even better, you could have a setAgeInMinutes() and a setAgeInYears() methods, which make it clear what the input should be.

You could do the same with getters - getAgeInMinutes() and getAgeInYears(). It doesn't matter how the data is stored internally, and it can be changed whenever the owner of that code wants - as long as she updates the getters and setters correctly, how the data is stored internally doesn't matter. She could even change it to storing it as a date.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
choubix alex

Joined: Dec 25, 2009
Posts: 22

Fred, Joe, Mark, Marco: thank you so much for spending of your time writing detailed answers.
I don't know yet if I'll be using multithreading (beginner with only 3 days of Java under my belt! ;) )
maybe it will be useful for what I intend to do but I have not yet reached that stage hehehe ;)

I dont foresen the company hiring programmers in the short term but I understand your point with the setters/getters.
Controlling the data stored in the variables is crucial (it can be quite messy if the code is not explicit! it's already quite difficult after a few days away from the office and when the code is not commented properly...) and can prevent users from storing something that shouldnt be there.
Marco Ehrentreich
best scout

Joined: Mar 07, 2007
Posts: 1294

No Problem

As you are new to Java, I would recommend not worry too much about more advanced topics like multithreading. But all the other points here are definitely true and you should think about them right from the beginning. Btw. it's not too much additional work to create getters and setters for some members. I think, today any modern Java IDE has some features to auto-generate such code fragments for the members you wish.

it can be quite messy if the code is not explicit! it's already quite difficult after a few days away from the office and when the code is not commented properly

Good point! A lot of people don't even think about this problem. As the examples above show it's often a good idea to use more reasonable names for getters/setters (basically for all identifiers). This saves you the time for lengthy comments and doesn't become outdated.

Luca Moretti

Joined: Dec 27, 2009
Posts: 2
At some point later in your Java-life, you might want to think about wether using getters and setters is actually an "Object-Oriented" thing to do.
choubix alex

Joined: Dec 25, 2009
Posts: 22
well, right now I am at the "embryonic stage" hahaha ;)

but you are right: I've read that the use of Setters/Getters is not fully "OO" compliant. Nevertheless I am really trying to get things to work at the moment.

next on my list is to :
- have a clear roadmap of what I want to develop in terms of functionalities and look/feel (java, swing + webstart / JavaFX)
- get hold of JDBC

Then I will certainly have to design an "infrastructure" for what I want to achieve and finally work on the performance and scalability of the application
(I suppose that means using: Maven 2, Subversion, Hudson, Jira -as hopefully I'll get someone on board late next year and that implementing all these tools would help working with someone else!)

And I am not mentioning the various packages that I will undoubtedly stumble upon when looking for reporting capabilities, charting etcetc...

I agree. Here's the link: http://aspose.com/file-tools
subject: setter / getter: doesnt make sense
It's not a secret anymore!