JAZWii
JAZWii

Reputation: 37

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

If I have this class and I want to initialize a new field of type Element, how can I 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); 
    }
}

Upvotes: 2

Views: 104

Answers (2)

Roman C
Roman C

Reputation: 1

Make the inner calss static

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

Upvotes: 1

sakura
sakura

Reputation: 2279

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.

Upvotes: 0

Related Questions