• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Christopher Laurenzano
Ranch Hand
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?

 
Ranch Hand
Posts: 174
Java ME Opera Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 79151
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Christopher Laurenzano
Ranch Hand
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Could you tell me what you mean by 'member' variable? Is it a synonym for instance variable?



Yes.
 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 7
MySQL Database Tomcat Server Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 4
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in the printout method instead of having this:



you should have this:



and this uses your getter method.

 
Geo Kinkladze
Greenhorn
Posts: 4
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[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
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Marshal
Posts: 79151
377
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In short - if you try to extract value from a void return it would give you compilation error !!!
 
Master Rancher
Posts: 4796
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I hope the original poster was not still waiting.
 
That's a very big dog. I think I want to go home now and hug this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic