javainitializationinner-classesclass-variables

How to initialize a new field of an inner class with constructor?


If I have this class and I want to initialize a new field of type Element, how I can do that

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

when I tried to do this it gave me an error:

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

Solution

  • Try this

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

    your inner class is not static so you need to create an object of outer class first.