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.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
Since the constructor is private , we cannot access it from outside the class. However, we can use enum constants to call the constructor. In the Main class, we assigned SMALL to an enum variable size . The constant SMALL then calls the constructor Size with string as an argument.
Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.
Because an enum is just another class type it can have constructors, fields and methods just like any other classes. Below we define a constructor that accept a string value of color code.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With