java enum变量,我们可以在Java枚举中包含变量和方法吗?

Java中的枚举(枚举)是一种存储一组常量值的数据类型。您可以使用枚举来存储固定值,例如一周中的天,一年中的月等。

您可以使用关键字enum定义枚举,后跟枚举的名称为-enum Days {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

}

枚举中的方法和变量

枚举类似于类,您可以在其中包含变量,方法和构造函数。枚举中仅允许使用具体方法。

示例

在下面的示例中,我们定义一个名称为Vehicles的枚举,并在其中声明五个常量。

除了它,我们还有一个构造函数,实例变量和实例方法。enum Vehicles {

//声明枚举的常量

ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;

//枚举的实例变量

int i;

//枚举的构造方法

Vehicles() {}

//枚举的方法

public void enumMethod() {

System.out.println("This is a method of enumeration");

}

}

public class EnumExample{

public static void main(String args[]) {

Vehicles vehicles[] = Vehicles.values();

for(Vehicles veh: vehicles) {

System.out.println(veh);

}

System.out.println("Value of the variable: "+vehicles[0].i);

vehicles[0].enumMethod();

}

}

输出结果ACTIVA125

ACTIVA5G

ACCESS125

VESPA

TVSJUPITER

Value of the variable: 0

This is a method of enumeration

示例

在下面的Java示例中,我们声明5个带有值的常量,我们有一个实例变量来保存常量的值,有一个参数化的构造函数对其进行初始化,以及一个getter方法来获取这些值。import java.util.Scanner;

enum Scoters {

//带值的常量

ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);

//实例变量

private int price;

//Constructor to initialize the 实例变量

Scoters (int price) {

this.price = price;

}

//静态显示价格的方法

public static void displayPrice(int model){

Scoters constants[] = Scoters.values();

System.out.println("Price of: "+constants[model]+" is "+constants[model].price);

}

}

public class EnumerationExample {

public static void main(String args[]) {

Scoters constants[] = Scoters.values();

System.out.println("Value of constants: ");

for(Scoters d: constants) {

System.out.println(d.ordinal()+": "+d);

}

System.out.println("Select one model: ");

Scanner sc = new Scanner(System.in);

int model = sc.nextInt();

//Calling the static 枚举的方法

Scoters.displayPrice(model);

}

}

输出结果Value of constants:

0: ACTIVA125

1: ACTIVA5G

2: ACCESS125

3: VESPA

4: TVSJUPITER

Select one model:

2

Price of: ACCESS125 is 75000

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值