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

问题描述 投票:0回答:2

如果我有这个类并且我想初始化一个类型为

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); 
    }
}
java initialization inner-classes class-variables
2个回答
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);
  }
}

0
投票

试试这个

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

你的内部类不是

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

© www.soinside.com 2019 - 2024. All rights reserved.