• 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

Assigning values to instance fields

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:


 
Ranch Hand
Posts: 492
Firefox Browser VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I like Steve's way better, and besides don't enum ordinal values start at 0?
 
reply
    Bookmark Topic Watch Topic
  • New Topic