How to use enums?
I'm not sure how to use enum in Java. Am I using it right in the following example?
enum Sex {M, F};
public class person{
private person mom;
private Sex sex;
public person(Sex sex){
this.sex = sex;
//is this how i'd set sex?
}
public void setMom(person mom){
if(mom.sex == 'M'){}
//is this how i would check to see if the sex of the passed person a开发者_高级运维rgument is male?
}
}
This is what you want to use:
if(mom.sex == Sex.M)
however, I would definitely spell out the enum constants as MALE and FEMALE.
In your case you should simply write:
public void setMom(person mom){
if(mom.sex == Sex.M){}
//is this how i would check to see if the sex of the passed person argument is male?
}
Please note that enums
allow you to check equality with ==
You can have a look to http://download.oracle.com/javase/tutorial/java/javaOO/enum.html for more information.
There is third possibility you might not have considered is null
. e.g. mom.sex could be MALE
, FEMALE
or null
If you what to validate I would write it as
if(mom.sex != Sex.FEMALE) // not the only valid option.
As an enum type may get more options over time, this is best practice IMHO.
A Person
should have a mom
when created/born. I would add this to the constructor and possibly not allow it to be changed. i.e. make the mom
and/or sex
final and drop the setter.
精彩评论