msd msd - 1 year ago 94
Java Question

Illegal modifier for the nested class

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download