2013-07-25 37 views
2

我有2个分类在不同的页面。Enum无法解析? Java

对象类:

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(); 
} 

错误有两个,一个是类型解决不了另一种是不倾斜导入。我能做什么?我第一次使用枚举,但你看到。

+0

查看Reimeus的答案应该被接受(包含'enum'的类不能在默认包中)。或[看这里](http://stackoverflow.com/questions/283816/how-to-access-java-classes-in-the-default-package)。 – mins

回答

9

enums需要在包中声明import语句才能工作,即不能从package-private(默认包)类中的类中导入enums。移动枚举包

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

另外,您可以使用完全合格enum

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

没有import语句

2

对于静态的方式在静态import语句给予适当的封装结构

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(); 
    } 
} 
2

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