在java中,这样的枚举类型是怎么编译的? [英] In java, What does such enum type compile to?

查看:97
本文介绍了在java中,这样的枚举类型是怎么编译的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 枚举公司{
EBAY(30),PAYPAL 10),GOOGLE(15),YAHOO(20),ATT(25);
private int value;

private Company(int value){
super(this.name());
this.value = value;
}

public int getValue(){
返回值;
}
}

内部编译为

  final class公司扩展Enum< Company> {
public final static公司EBAY =新公司(30);
public final static公司PAYPAL = new Company(10);
public final static公司GOOGLE =新公司(15);
public final static公司YAHOO =新公司(20);
public final static公司ATT =新公司(25);

private int value;

private Company(int value){
super(this.name(),Enum.valueOf(Company.class,this.name()));
this.value = value;
}

public int getValue(){
返回值;
}
}

我的理解是否正确?

解决方案

功能上是的。字面上没有(你不能明确地分类枚举为一件事情)。 枚举有一个 toString 。而您的枚举不是有效的代码(您不能调用 super())和 getValue 需要返回类型。

 枚举公司{
EBAY(30) PAYPAL(10),GOOGLE(15),YAHOO(20),ATT(25);
private int value;

私人公司(int value){
this.value = value;
}

public int getValue(){
返回值;
}
}


Below is the code that defines enum type.

enum Company{
    EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
    private int value;

    private Company(int value){
        super(this.name()); 
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}

that gets internally compiled to,

final class Company extends Enum<Company>{
    public final static Company EBAY = new Company(30);
    public final static Company PAYPAL = new Company(10);
    public final static Company GOOGLE = new Company(15);
    public final static Company YAHOO = new Company(20);
    public final static Company ATT = new Company(25);

    private int value;

    private Company(int value){
        super(this.name(),Enum.valueOf(Company.class, this.name()));
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}

Is my understanding correct?

解决方案

Functionally, yes. Literally no (you can't explicitly sub-class Enum for one thing). enum(s) have a toString. And your enum isn't valid code (you can't call super()) and getValue needs a return type.

enum Company{
    EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
    private int value;

    private Company(int value){
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}

这篇关于在java中,这样的枚举类型是怎么编译的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆