| Author |
Assigning values to instance fields
|
Ted Scofield
Greenhorn
Joined: Apr 04, 2009
Posts: 26
|
|
Hi guys,
Suppose I have a class Person with instance fields
I would like to assign an int value to all the instance fields, for example: name = 1, surname = 2, currentAge = 3. But this mustn't change the original value of a field.
Example:
Suppose class Person has a method
Then the output of print(1) should be Ted.
I was trying to do this with a switch sentence but since the fields are of different data type, I am now stuck. Could you think of any elegant solution?
Thanks,
Ted
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26141
|
|
Ted,
Take a look at the "enum" keyword in Java. This lets you use constants to refer to things. You could use an enum instead of the int. Then a switch could map the enum value to your type.
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3026
|
|
Why do you want to do that?
Anyway, one way would be to use static constants in the Person class to translate between the field you want to display and the integer input. For example:
|
Steve
|
 |
Hunter McMillen
Ranch Hand
Joined: Mar 13, 2009
Posts: 490
|
|
|
I like Steve's way better, and besides don't enum ordinal values start at 0?
|
"If the facts don't fit the theory, get new facts" --Albert Einstein
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: Assigning values to instance fields
|
|
|