如何使用构造函数初始化内部类的新字段?

时间:2014-03-29 09:20:03

标签: java initialization inner-classes

如果我有这门课,我想初始化Element类型的新字段, 我该怎么做

public class MyLinkedList{

   protected Element head, tail;

   public final class Element{
      Object data;
      int priority; 
      Element next;

      Element(Object obj, int priorit, Element element){
       data = obj;
       priority = priorit;
       next = element;
      }
   }
}

当我尝试这样做时,它给了我一个错误

public class PriorityTest{
    public static void main(String[]args){  
        MyLinkedList.Element e1 = new MyLinkedList.Element("any", 4, null); 
    }
}

2 个答案:

答案 0 :(得分:1)

使内部类静态

public class MyLinkedList{

   protected Element head, tail;

   public static final class Element{
      Object data;
      int priority;
      Element next;

      Element(Object obj, int priorit, Element element){
       data = obj;
       priority = priorit;
       next = element;
      }
   }

  public static void main(String[]args){
      MyLinkedList.Element e1 = new MyLinkedList.Element("any", 4, null);
  }
}

答案 1 :(得分:0)

试试这个

MyLinkedList.Element e1 = new MyLinkedList().new Element("any", 4, null);

你的内部类不是static所以你需要先创建一个外部类的对象。