enum枚举构造函数

enum枚举构造函数

Example: enum Constructor

enum Size {

   // enum constants calling the enum constructors 
   SMALL("The size is small."),
   MEDIUM("The size is medium."),
   LARGE("The size is large."),
   EXTRALARGE("The size is extra large.");

   private final String pizzaSize;

   // private enum constructor
   private Size(String pizzaSize) {
      this.pizzaSize = pizzaSize;
   }

   public String getSize() {
      return pizzaSize;
   }
}

class Main {
   public static void main(String[] args) {
      Size size = Size.SMALL;
      System.out.println(size.getSize());
   }
}

Output

The size is small.

In the above example, we have created an enum Size. It includes a private enum constructor. The constructor takes a string value as a parameter and assigns value to the variable pizzaSize.

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.

Finally, we called getSize() using size.

在上面的示例中,我们创建了一个枚举Size。它包含一个private枚举构造函数。构造函数将字符串值作为参数,并将值分配给变量 pizzaSize

由于构造函数是 private,我们无法从类外部访问它。但是,我们可以使用枚举常量来调用构造函数。

在里面 Main 类,我们将SMALL分配给一个枚举变量 size。常数 SMALL 调用构造函数 Size 以字符串作为参数。

最后,我们**getSize()**使用 Size

原文:https://www.programiz.com/java-programming/enum-constructor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值