• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assigning values to instance fields

 
Ted Scofield
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author & internet detective
Marshal
Posts: 34072
333
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like Steve's way better, and besides don't enum ordinal values start at 0?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic