简体   繁体   English

构造函数中的Java枚举

[英]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. 我有一个enum性别的类人员,在Person Constructor中我想初始化性别和年龄。 How can i instantiate a new Person in main() method? 如何在main()方法中实例化一个新Person?

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. 但是,每次需要指定枚举值时,由封闭类的Person为枚举加前缀是笨拙的。

So add the correct import in the client class. 因此,在客户端类中添加正确的导入。 The IDE automatic imports feature should do it for you. IDE自动导入功能应该为您完成。

import Person.Gender;

and use a straighter way : 并使用更直接的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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