Why different class files are created for each enum type if they have constant-specific method?

前端 未结 2 431
既然无缘
既然无缘 2021-01-21 06:42

i have one enum as

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

  private String opcodes;

  private OperationsType(String opcodes)          


        
2条回答
  •  孤独总比滥情好
    2021-01-21 07:06

    Consider the following class:

    public class Test {
        public double testApply(Operations operation, double a, double b) {
            return operation.apply(a, b);
        }
    
        public static void main(String[] args) {
            Test test = new Test();
            assert 3.0 == test.testApply(OperationsType.ADD, 2.0, 1.0);
            assert 1.0 == test.testApply(OperationsType.SUB, 2.0, 1.0);
        }
    }
    

    In the body of method testApply the compilier doesn't know the exact type of the argument operation (is it ADD or SUB?), it only knows that it is an instance of type Operations. In order to dispatch the invocation of apply correctly, the VM needs to know the runtime type of the argument. However if you only have one class for all values that would be impossible. Therefore the compiler creates different classes for each value and dispatches the invocation according to the run-time type.

    On the other hand, if you do not define any constant specific methods then there is no need to create subclasses, since there are no operations that must be dispatched depending on the runtime type of the receiver object. Hence the compiler simply omits the generation of these classes.

提交回复
热议问题