3

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 try 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); 
    }
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
JAZWii
  • 47
  • 6
  • Since the inner class is not static, an instance of the inner class cannot exist on it's own. If this is what you want, declare the inner class static. – NilsH Mar 29 '14 at 09:24

2 Answers2

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);
  }
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • thank you a lot but when I tried to compile it it shows me this error: error: an enclosing instance that contains MyLinkedList.Element is required MyLinkedList.Element e1 = new MyLinkedList.Element(new String("any"), 4, null); – JAZWii Mar 29 '14 at 09:25
0

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.

sakura
  • 2,249
  • 2
  • 26
  • 39
  • 1
    Or, if the Element class doesn't need to refer to the list's `head` and `tail` then make it a static class instead of an inner class. – Ian Roberts Mar 29 '14 at 09:29