简体   繁体   中英

Java enum in Constructor

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.

Use

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM