Reputation: 971
I am trying to learn 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.
Upvotes: 11
Views: 11487
Reputation: 347332
First, you need to create field of type gender
...
private gender aGender;
Then you need to change the constructor to take a reference to an object of type 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
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
Upvotes: 8
Reputation: 1513
If you have enum Gender
defined, you can directly pass Gender
to constructor, change as
public Person(int age, int weight, int height, String name, Gender gender)
Upvotes: 2
Reputation: 10522
The enum type you defined has name gender
, therefore you need to pass it as
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}
Upvotes: 1