在Java中用于引用变量的枚举

huangapple go评论71阅读模式
英文:

enumeration for reference variable in Java

问题

我正在学习引用变量。如果我有两个类:假设一个是 Person,另一个是继承自 Person 类的 Minnesotan。Person 类是抽象的。在 Person 类中,有一个称为 Gender 的引用变量,它可以是 female、male 和 others。我该如何编写具有枚举的引用变量 Gender?引用变量如何在子类中扩展?如果这是重复的问题,我很抱歉,并提前感谢您的帮助。

public abstract class Person{
   public static Gender gender;
   class Gender{

   }
   public enum Gender{
       female, male, others;
   }
}

public class Minnesotan extends Person{
    public Minnesotan(Gender gender){
        super(gender);
    }
}
英文:

I am learning reference variables. If I have two classes: let’s say one is Person and the other is Minnesotan which extends Person class. The Person class is abstract. In the Person class, there is a reference variable called Gender which can be female, male and others. How can I write the reference variable Gender which has enumeration? how the reference variable can be extended in child class? Sorry if it is duplicate question and thank you in advance for your help.

public abstract class Person{
   public static Gender gender;
   class Gender{

   }
   public enum Gender{
       female,male,others;
   }
}
public class Minnesotan extends Person{
    public Minnesotan(Gender gender){
        super(gender);
    }

}

答案1

得分: 2

开始枚举定义部分:

public enum Gender{
    男性,
    女性
}

您可以使用该枚举的引用,类型为 Gender,可以是 男性 或者 女性,就像其他变量一样。例如,

Gender 男性 = Gender.男性;
if (男性 == Gender.男性){
    System.out.println("变量 男性 的值为 Gender.男性");
} else {
    System.out.println("变量 男性 的值为 Gender.女性");
}

现在是 Person 类:

public abstract class Person{
    public Gender gender;
}

静态修饰符被移除,因为每个 Person 实例应该拥有自己的性别。

最后是 Person 的实际实现,即 Minessotan 类:

public class Minnesotan extends Person{
    public Minnesotan(Gender gender){
        this.gender = gender;
    }
}

为了创建一个 Minessotan,它是一个 Person,您必须提供它的性别,类型为 Gender。就是这样。

英文:

Let's start with the enumeration,

public enum Gender{
 Male,
 Female
}

You can use references of that enumeration which will be of type Gender and can be either Male or Female like any other variables, for example,

Gender male = Gender.MALE;
if (male == Gender.MALE){
 System.out.println("Variable male has value Gender.MALE");
}else{
 System.out.println("Variable male has value Gender.FEMALE");
}

Now the Person class,

public abstract class Person{
 public Gender gender;
}

Static modifier is removed because each instance of Person should have each own gender.

And finally an actual implementation of Person, a Minessotan,

public class Minnesotan extends Person{
 public Minnesotan(Gender gender){
     this.gender = gender;
 }
}

In order to create a Minnesotan, which is a Person, you must provide it's gender, which is of type Gender. That's it.

huangapple
  • 本文由 发表于 2020年5月30日 18:34:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/62101169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定