File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Assigning values to instance fields Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Assigning values to instance fields" Watch "Assigning values to instance fields" New topic

Assigning values to instance fields

Ted Scofield

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.

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?

Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33117

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

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:

Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

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:
subject: Assigning values to instance fields
It's not a secret anymore!