本文介绍了如果具有特定于常量的方法,为什么要为每种枚举类型创建不同的类文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举

enum OperationsType {
  ADD("+"), SUB("-"), DIV("/"), MUL("*");

  private String opcodes;

  private OperationsType(String opcodes) {
    this.opcodes = opcodes;
  }

  public String toString() {
    return this.opcodes;
  }
}

这里所有的枚举类型都没有任何constant Specific method,因此javac仅为enum创建一个类文件,作为

Here all enum type doesn't have any constant Specific method so javac is creating only one class file for enum as

OperationsType.class

但是如果我为所有枚举类型在同一代码中添加constant Specific method,则javac正在创建5个类文件.

but if i add constant Specific method in same code for all enum type then javac is creating 5 class files.

Operations.class
Operations$1.class
Operations$2.class
Operations$3.class
Operations$4.class

获取以下代码

enum Operations {
ADD("+") {
    public double apply(double a, double b) {
        return a + b;
    }
},
SUB("-") {
    public double apply(double a, double b) {
        return a - b;
    }
},
DIV("/") {
    public double apply(double a, double b) {
        return a / b;
    }
},
MUL("*") {
    public double apply(double a, double b) {
        return a * b;
    }
};

private String opcodes;

private Operations(String opcodes) {
    this.opcodes = opcodes;
}

public abstract double apply(double a, double b);
}

所以我对此感到怀疑,为什么compiler如果每个enum type具有constant Specific method,则为每个enum type创建4个不同的类,而如果它们没有constant Specific method,却不创建不同的类呢?

So i have doubt that why compiler has created 4 different classes for each enum type if they are having constant Specific method but not creating different classes if they don't have constant Specific method?

推荐答案

具有特定于常量的方法的枚举是使用匿名内部类实现的.如 Java语言规范中所述:

Enums with constant-specific methods are implemented using anonymous inner classes. As mentioned in The Java Language Specification:

匿名内部类是通过创建名称如OuterClass$1OuterClass$2等的类文件来实现的,在枚举的情况下正是这种情况.

Anonymous inner classes are implemented by creating class files with names like OuterClass$1, OuterClass$2 etc., and this is exactly what happens in the case of the enum.

这篇关于如果具有特定于常量的方法,为什么要为每种枚举类型创建不同的类文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 10:56