This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes explanation of getter/setter methods -- what's the difference exactly? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "explanation of getter/setter methods -- what Watch "explanation of getter/setter methods -- what New topic
Author

explanation of getter/setter methods -- what's the difference exactly?

Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
I don't quite understand the difference between getter/and setter methods. Here's a code example from Head First Java:


I don't quite understand the difference between the getter and setter methods and why they're used -- they both give a value.

And by the way, related to another post I made, I noticed as well that the void modifier for the methods still produce a value, so what is the difference between that and using a return value?
Billy Korando
Greenhorn

Joined: Sep 18, 2009
Posts: 15
Getter and setter methods are used to retrieve and manipulate private variables in a different class. A "getter" method does as it name suggest, retrieves a the attribute of the same name. A setter method allows you to set the value of the attribute.


Check out my blog on software development: http://www.turnleafdesign.com
Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
Forgive me for being dense, but I don't quite get it. Could you (or anyone else, for that matter) walk me through the code example and explain what's going on regarding the setter and getter methods?

Zandis Murāns
Ranch Hand

Joined: Aug 18, 2009
Posts: 174

When you are accelerating your car cars accelerator pedal in your game, you do car.setSpeed(increased_value);
To read the current speed (for example, to display it on screen or calculate some physics), you do car.getSpeed() and use that value as you want to.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37883
    
  22
Getters and setters allow control over the values passed. It may for example be possible to validate the valuesThe get method can allow a copy of a field to be returned; since the Water object returned is different from that in the Kettle class, other code can alter its temperature without affecting the Kettle object. Also note that the temperature is stored indirectly in the Water object, which is an implementation detail that people writing any other code know nothing about.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

The difference between getter and setter methods is obvious: a getter method gets the value (of a member variable), a setter method sets the value (of a member variable). Don't you see that, or did you really mean something else?

The reason to use getter and setter methods rather than just making the member variables public is because of the principle of information hiding - classes should not reveal their innards to the outside world, because that tightly couples the implementation of the class to whatever is in the outside world. That's bad, because if you tightly couple lots of classes together in a larger program, the program will become a big, entangled mess that's hard to maintain.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
Could you tell me what you mean by 'member' variable? Is it a synonym for instance variable?

Also -- where should the getter and setter methods go -- can it be an any class or not?
M K Rayapudi
Ranch Hand

Joined: Feb 19, 2007
Posts: 157
Could you tell me what you mean by 'member' variable? Is it a synonym for instance variable?


Yes.


R6i
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Christopher Laurenzano wrote:Also -- where should the getter and setter methods go -- can it be an any class or not?

Any class that has member variables = instance variables that you want to be able to access outside the class.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11149
    
  16

I don't quite understand the difference between the getter and setter methods and why they're used -- they both give a value.

But they DON'T.

Your setter takes in a value, but returns nothing - that's what 'void' means. you can't call the setter and assign it to a variable:

int value = setTime("fred");

Another purpose of a setter is to validate input. Does it make sense to set the time to 'fred'? probably not. usually your setter will have code to make sure what you are trying to send in is valid - or throw some kind of error message.


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

Joined: Sep 22, 2009
Posts: 8
when you run the program

# program starts in mains
# object c is created
# function set time is called by the object c
# the variable time is set to the value passed by
# function get time is called by object c
# the time is returned
# it will passe to tod
# tod get printed out

hope this will help youu


_rohith
Chris John
Greenhorn

Joined: Sep 19, 2009
Posts: 7

Getter and Setter methods aid in data encapsulation. Actually you can design programs without using them and javac won't complain. But in that case since your variables are declared public it would easier to tamper with from outside. By using getter and setter methods you make sure your variables are only set in a way you decide. In your code in Clock class you ned to declare a private String time.
Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
I thought I'd post a little program I wrote here which uses getter and setter methods. It's the very beginnings of a program to enter and alphabatize my cd collection, according to either Album Title, Artist, lable (or any other criteria I decide.). Mind you this isn't final version by any means - I'm writing it as I go and learn about Java, so I make changes to the program as I learn more. But I thought I'd make this my long term project rather that do it in Excel, for example. At this point, it only asks for the CD information and prints it out. At the moment, it only is using an array, but I know that won't work in the future, because the program is supposed to take in a theoretically limitless amount of information, but I haven't learned how to do that yet. The Scanner function I learned from Java for dummies, not from HFJ yet. Here's the code:





Now, there are a couple of questions about this I'd like to ask:

First, please let me know if I could have written it better -- an extraneous, redundant or missing code, etc.

Second, the program compiled and ran fine, but it ran fine anyway even if I take out the calls to the getter methods in the second while loop, so I've missed something about the getter methods, but I can't figure out exactly what. Could someone out there please let me know what it is? I'm guessing that maybe they're not being used in the program at all, but I'm not sure.
Billy Korando
Greenhorn

Joined: Sep 18, 2009
Posts: 15
Some ways this program could have been written better:
If you know how long you will run a loop for, then it is better to use a for loop


The reason why the program "works" when you take out the calls to the getters is because they are not used. In printout() you are accessing those variables you want to display locally. You should simply remove the getter calls, as like you noticed, they do not affect how the programs runs.

Also you are not properly "camel casing" your methods. The first word is correctly lower case, however every subsequent new word should have the first letter be upper case (e.g. setYearOfRelease). Also you should explicitly define your setters as public. I believe the default setting is protected, which means if you tried accessing these methods from a different package you would get a compiler error saying you cannot access said method.
Geo Kinkladze
Greenhorn

Joined: Sep 22, 2009
Posts: 4
in the printout method instead of having this:



you should have this:



and this uses your getter method.

Geo Kinkladze
Greenhorn

Joined: Sep 22, 2009
Posts: 4
Christopher,

I don't quite understand the difference between the getter and setter methods and why they're used


I would guess you are confused because you don't understand why you create programs which force you to use



instead of



If we were to add another variable to the clock class such as

String alarmTime;

and in the Setter Method put the following pseudocode:

void setAlarmTime (String t)
if t is between 6:00am and 8:00 am
then set AlarmTime to t;
Else
System.out.println("Sorry but Mum specifically says you must get up in time for School/work/chores");
set AlarmTime to 8:00 am;

Do you see why you would force the use of this settermethod in this case. It stops the alarm being set outside an allowed range. So in this case nobody could just type

and steal a lie in.

Equally by not allowing the method to be publicly available you stop the following from happening



Seriously though.. it helps stop variables from going outside ranges they're not supposed to, it allows you to force some extra code to be run when a variable changes and all this can be done in one neat little place inside the setter method.

A good reason to have a getter method would be one that returns a string representing your location. You could force the method making the call (or asking you your location) to identify themselves.

if personAsking = wife then return "at office"
if personAsking = boss then return "with customer"
if personAsking = golfbuddy then return "on my way"

I'm sure you can work out your own advantages with this

I noticed as well that the void modifier for the methods still produce a value, so what is the difference between that and using a return value?


This one is harder to get into your brain and understand what you are saying but what I think you mean is that you have noticed that the void method makes something equal something so therefore (in your mind) it produces a value. I've heard it best explained this way (Barry Burd I think in "OO for dummies"): With most Void methods you are only interested in the side effect of the method, i.e the method carries something out for you and then quietly dies.

So the time setter method sets the time of the clock whereas the getter method gives you an answer. With a getter method you ask the question and the answer given to you is the return value of the method. With the setter method you didn't ask a question and therefore didn't get an answer.

Hope I didn't confuse you further with all this.
Billy Korando
Greenhorn

Joined: Sep 18, 2009
Posts: 15
Geo Kinkladze wrote:in the printout method instead of having this:



you should have this:



and this uses your getter method.



That would add unnecessary overhead of a method call when you can already access the member directly. The way Christopher wrote it is correct (in that area at least).
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37883
    
  22
I am surprised nobody has commented on the real problem with the CD class. You have no constructor. It looks good to use all those "set" methods and it allows you to play with them, but a real CD (call the class "CD" not "CDList" since it isn't a list of any kind) doesn't change its title ever. (Not even if you put it in the wrong jewel case !)

You should have something like thisYou can now miss out the set methods and you have (well, more-or-less) an immutable class. Once you have set up your title, it remains the same for ever. You ought really to have quite a lot of things declared final for real immutability. Now you can initialise each CD in the array, and you will not have problems with any of the values being null, even if you manage to get a C issued in the year -987519849 You should be able to see in that last code block something which ought to be refactored into a separate method because there is repeated code.

People said you didn't use your get methods. You did. There are 4 get calls in the last for-loop, which return their results. But you don't do anything with those returned values. This code . . . : . . . gets the 4 values, and they are not used farther. So they vanish into cyber-limbo never to be seen again.

By the way: you are indenting your code incorrectly, and you should use spaces not tabs. The comments you posted earlier in "CODE" were too long and caused horizontal scroll bars to appear; I had to edit a post to make the whole thread easier to read.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37883
    
  22
Welcome to the Ranch , Geo Kinkladze

I like the idea of the method which returns different values depending on the person asking, but that is not an ordinary get method.
An ordinary get method returns the same type as the field it is "getting" and does not take any arguments.
An ordinary set method takes the same type as the field it is "setting" and often has a void return type, ie it doesn't return anything.

I don't understand what Christopher Laurenzano means about
the void modifier for the methods still produce a value
By the way: "void" isn't called a modifier, but a return type. Modifiers include public final private and static, but not void.

Geo Kinkladze
Greenhorn

Joined: Sep 22, 2009
Posts: 4
[quote] I like the idea of the method which returns different values depending on the person asking, but that is not an ordinary get method. [/quote]

Yeah, sorry I probably shouldn't have used that example. I guess I should explain where I used this type of getter.

In my current company we have a system that holds data for parts we produce. We set up manningLevel and partWeight as int, having been told that under no circumstances would they ever need to be anything but. This was good for about two years, but then the business started making smaller more intricate parts. Suddenly we needed 0.2 manning levels and 5.6 grammes in addition to the existing 1,2 or 3 man jobs weighing 160-500 grammes. We changed the int to double in the part class and got clobbered. I still shudder thinking about the hours I lost. You see we had tons of getters that we had built up over the years, all expecting an int, with calculations built thereon. So from that day I resolved to make getters identify themselves.. Not all of course, just those I marked as "suspect". Then I made the method keep a record of who called them. I guess the solution was worse than the problem but I am getting over it. I've resolved to "knock it down and start over" one day, when I understand Java better. Thats probably why I'm here.
Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
I've got a new problem with my code -- all of a sudden, I can't enter a name for the Record Label -- after I'm done enter the year of Release, it just prints "Record Label:" and goes the next entry for the Artist Name. I don't remember making any changes to the code, that would do this, so I'm stumped. Can anyone help me out?

Here's the code again (I also added some code to allow the user to enter a record number and print out the info for that record . Here's the code again:

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37883
    
  22
It is Scanner at fault.

You are asking for nextInt, then nextLine. [rant]You have posted code which won't work (read this FAQ) because you are passing an int and your other class takes a String. You also appear not to have read what you were told earlier, eg about those "get" methods where you never use the result of what you are "get"ting.
The correct spelling of getLabel is getLabel. You have getLabel in one place, and getlabel in another.[/rant]

Back to your nextInt. What you are trying to pass is something like:

the Beatles↩
Sergeant Pepper↩
1969↩
Apple Records↩

where "↩" means return key. So you read "the Beatles" as your first "line" then you read "Sergeant Pepper" as the second "line" then you read an int "1969". After 1969, the Scanner takes the remainder of the line, after 1969 and before ↩ as its next result. That now looks like this: "". Yes, the empty String. So you get the empty String as your label. If you pass this line:

1969 Apple Records↩

then you get "Apple Records" as your record label.

Suggested solution. You will have to do this every now and again with Scanner, so make sure to remember this next time you have the same problem.

Call the nextLine() method immediately after nextInt() and discard the returned value. Just writeThat will ensure the number of lines passed and the number of lines called is the same.
Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
Campbell Ritchie --

Thanks for your solution. I didn't read anything about that regarding Scanner in the other book I had -- I switched over to HFJ and I haven't got to Scanner yet. I haven't gotten to anything about immutability yet either -- according to the index, it's on pae 661 of HFJ and I'm only on page 100, so it'll be a while before I get there.

Regarding your comment on not using the getter methods, I update my code, per the advice of Billy Kordan, regarding the use of the getter methods, but didn't post the updated code. Here it is:


Is that what you meant?

By the way, I tried using bold and colors to make the updated code stand out, but nothing happened -- only html tags in the post preview. I unchecked "Disable HTML in this message" but that didn't help either. What am I missing
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37883
    
  22
I didn't advise not to use getter methods; I did suggest using a constructor and avoiding the setter methods earlier, however.

You have misunderstood what people said about your not using getter methods. You do in fact call the getter methods several times, but you make no use of the returned values. I have told you that twice already.
Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
So, since I'm still obviously not getting it, what should I have done/written to use those returned values?

I haven't read anything about constructor methods yet, either. That's why I haven't used one.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37883
    
  22
Sorry, I seem to have missed this thread for a week.
Hope I am not too late replying. It was in your CDListTestDrive class you were calling get methods and doing nothing with the result in lines 38-41.
For constructors (not called methods, please ) start here.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: explanation of getter/setter methods -- what's the difference exactly?
 
Similar Threads
Java assignment issues
Not sure why there is a line in this code...
Difference between Reference Data Types & Own Objects
Calling variable directly vs getter method
Getter and Setter In Java Bean