枚举类型(enum)实现接口

Ref-Gonçalo Marques

Introduction

java中的接口有时也可以通过枚举类型来实现。

The Enum

这里以一个简单的数学算法为例。首先我们定义一个运算的接口。

Operator.java
public interface Operator {
  int calculate(int firstOperand, int secondOperand);
}

接下来我们定义一个实现上面接口的枚举类型。

EOperator.java
public enum EOperator implements Operator {
  SUM {
    @Override
    public int calculate(int firstOperand, int secondOperand) {
      return firstOperand + secondOperand;
    }
  },
  SUBTRACT {
    @Override
    public int calculate(int firstOperand, int secondOperand) {
      return firstOperand - secondOperand;
    }
  };
}

接下来定义一个operation class

public class Operation {
  private int firstOperand;
  private int secondOperand;
  private EOperator operator;
  public Operation(int firstOperand, int secondOperand, 
                    EOperator operator) {
    this.firstOperand = firstOperand;
    this.secondOperand = secondOperand;
    this.operator = operator;
  }
  public int calculate(){
    return operator.calculate(firstOperand, secondOperand);
  }
}

最后测试:

public class Main {
  public static void main (String [] args){
    Operation sum = new Operation(10, 5, EOperator.SUM);
    Operation subtraction = new Operation(10, 5, EOperator.SUBTRACT);
    System.out.println("Sum: " + sum.calculate());
    System.out.println("Subtraction: " + subtraction.calculate());
  }
}

你可能感兴趣的:(枚举类型(enum)实现接口)