2

i have a class person with a enum Gender and in the Person Constructor i want to initialize the gender and age. How can i instantiate a new Person in main() method?

class Person  {

   public enum Gender { M,F }

   int age;
   Gender gender;

   public Person(int age, Gender gender) {
       this.age=age; this.gender=gender;
   }           
}

public static void main(String[] args) {
    Person p = new Person(20, ?);        
}

Best Regards.

6
  • 4
    Person p = new Person(20, Person.Gender.M); just like any nested static class (which is what a nested enum is). Commented Apr 2, 2018 at 20:59
  • ah thanks a lot, i have only tried Gender.M and other stuff. Commented Apr 2, 2018 at 21:01
  • Answer provided since someone just copied my comment word for word and presented it as an answer. Not cool. Commented Apr 2, 2018 at 21:03
  • @DontKnowMuchButGettingBetter And completely permissible here on SO. You want to write an answer, write an answer. Commented Apr 2, 2018 at 21:08
  • 1
    @chrylis: permissible maybe, but doesn't really pass the "smell test". At least he should have changed the wording a little bit, no? Commented Apr 2, 2018 at 21:24

2 Answers 2

8

Use

Person p = new Person(20, Person.Gender.M);

Note that a nested enum is accessed like a nested static class.

Sign up to request clarification or add additional context in comments.

Comments

2

Person p = new Person(20, Person.Gender.M); works of course.

But it is clumsy enough to prefix the enum by the Person enclosing class at each time you need to specify an enum value.

So add the correct import in the client class. The IDE automatic imports feature should do it for you.

import Person.Gender;

and use a straighter way :

Person p = new Person(20, Gender.M);

2 Comments

Nice, 1+. You could also static import the Gender and then pass in M or F, useful if used a lot in the program.
@DontKnowMuchBut Getting Better Indeed ! Import features may make the code much more readable as used finely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.