简体   繁体   English

将简单的枚举传递给Java中的构造函数

[英]Pass a simple enum into a constructor in Java

I am trying to learn Java. 我正在努力学习Java。 I would like to have a enum as a parameter in the constructor. 我想在构造函数中有一个枚举作为参数。 But I am getting an error. 但是我收到了一个错误。

public class Person {

    private int age, weight, height;
    private String name;

    private enum gender {MALE, FEMALE}

    public Person(int age, int weight, int height, String name, enum gender) {
         this.age    = age;
         this.weight = weight;
         this.height = height;
         this.name   = name;
         this.gender = gender;
    }
}

How would I handle the gender? 我该如何处理性别? I've tried with just gender and that didn't work either. 我尝试过性别,但也没用。

First, you need to create field of type gender ... 首先,您需要创建gender类型的字段...

private gender aGender;

Then you need to change the constructor to take a reference to an object of type gender 然后,您需要更改构造函数以引用属性类型的gender

public Person(int age, int weight, int height, String name, gender aGender) {

Then you need to assign the parameter to your field... 然后你需要将参数分配给你的领域......

this.aGender = aGender;

You gender enum should also be public 你的gender enum也应该是public

public enum gender {
    MALE, FEMALE
}

Otherwise, no one will be able to use it 否则,没有人能够使用它

For example... 例如...

public class Person {

    private int age, weight, height;
    private String name;
    private gender aGender;

    public enum gender {
        MALE, FEMALE
    }

    public Person(int age, int weight, int height, String name, gender aGender) {
                 this.age = age;
        this.weight = weight;
        this.height = height;
        this.name = name;
        this.aGender = aGender;
    }
}

You might like to have a read through Code Conventions for the Java TM Programming Language , it will make it easier for people to read your code and for you to read others 您可能希望阅读Java TM编程语言的代码约定 ,它将使人们更容易阅读您的代码并让您阅读其他代码

如果您定义了enum Gender ,则可以直接将Gender传递给构造函数,更改为

public Person(int age, int weight, int height, String name, Gender gender)

The enum type you defined has name gender , therefore you need to pass it as 您定义的枚举类型具有名称gender ,因此您需要将其作为传递

gender eGender

Just a comment. 只是评论。 By the convention all the self defined types (class names, interface names, enum names) should begin with a capital letter. 按照惯例,所有自定义类型(类名,接口名,枚举名)都应以大写字母开头。

So in this case it would be better if you named your enum type like this. 所以在这种情况下,如果你像这样命名你的枚举类型会更好。

private enum Gender {MALE, FEMALE}

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

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