-3
public class Deque<Item> implements Iterable<Item> {

    private int N; // size of the list
    private Node first;
    private Node last;


    public Deque() {


        private class Node {
            private Item item;
            private Node next;
            private Node prev;

        }
    }
}

I keep getting an error that I have an illegal modifier for my private class Node and that only final or abstract is permitted. But the Node class can't stand on its own so I don't think static is needed. Is there something wrong with how the item and the Nodes are declared in the private class? How can I resolve this error?

msd
  • 11
  • 6

2 Answers2

4

Your logic is basically sound. The main flaw is that you're attempting to define the class inside the constructor whereas you should be defining it directly inside Dequeue:

public class Deque<Item> implements Iterable<Item> {

    private class Node {
        private Item item;
        private Node next;
        private Node prev;
    }

    ...
}

Defining a class inside a method is permissible, but it's not what you need here. For background, see Use of class definitions inside a method in Java

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

You can define classes in blocks (like methods and constructors), they are called Local classes.

However, just like you can't declare a local variable as private, protected or public, you also can't declare a local class with an access modifier - because it doesn't make sense to. A local class is only visible inside the defining method.

If you really intend to declare a local class, remove the access modifier. But since you are declaring fields in the top-level class of type Node, you can't declare it as a local class: just move it outside the constructor.


Just picking up on your comment about "I don't think static is needed": I don't think static is not needed. Adding static to nested classes should be your default action, unless you actually need to refer to the containing Deque instance from the Node instances.

The thing is that each of the Node classes will have a hidden reference to the Deque, in order that you can access the Deque instance via Deque.this. If you don't need this reference, you can cut down on the memory used by not using it, which you do by making the nested class static.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243