5

我有 2 个分类在不同的页面。

对象类:

public class Sensor {

  Type type;
  public static enum Type
  {
        PROX,SONAR,INF,CAMERA,TEMP;
  }

  public Sensor(Type type)
  {
  this.type=type;
  }

  public void TellIt()
  {
      switch(type)
      {
      case PROX: 
          System.out.println("The type of sensor is Proximity");
          break;
      case SONAR: 
          System.out.println("The type of sensor is Sonar");
          break;
      case INF: 
          System.out.println("The type of sensor is Infrared");
          break;
      case CAMERA: 
          System.out.println("The type of sensor is Camera");
          break;
      case TEMP: 
          System.out.println("The type of sensor is Temperature");
          break;
      }
  }

  public static void main(String[] args)
    {
        Sensor sun=new Sensor(Type.CAMERA);
        sun.TellIt();
    }
    }

主类:

import Sensor.Type;

public class MainClass {

public static void main(String[] args)
{
    Sensor sun=new Sensor(Type.SONAR);
    sun.TellIt();
}

错误有两种,一种是无法解析类型,另一种是无法导入。我能做些什么?我第一次使用枚举,但你看。

4

3 回答 3

10

enums需要在包中import声明才能使语句起作用,即enums无法从包私有(默认包)类中的类导入。将枚举移动到包中

import static my.package.Sensor.Type;
...
Sensor sun = new Sensor(Type.SONAR);

或者,您可以使用完全合格的enum

Sensor sun = new Sensor(Sensor.Type.SONAR);

没有导入语句

于 2013-07-25T12:36:38.703 回答
2

static 关键字对枚举没有影响。使用外部类引用或在其自己的文件中创建枚举。

于 2013-07-25T14:00:28.027 回答
2

对于静态方式,在静态导入语句中给出正确的包结构

import static org.test.util.Sensor.Type;
import org.test.util.Sensor;
public class MainClass {
    public static void main(String[] args) {
        Sensor sun = new Sensor(Type.SONAR);
        sun.TellIt();
    }
}
于 2013-07-25T12:48:24.290 回答