javastaticinner-classes

In java, can nested class object use the enclosing class method?


I created a simple list class. What I want to do is to create a method in SLList to give the size a SLList object. I want to do it recursively, however, the following size() method I created just does not work. I know other ways to realize it such as creating a helper method. But what I am curious about is that why does my size() does not work? The error message is the "size() is undefined for SLList.IntNode". Why? Since I made the nested IntMode class just public and non-static, why it cannot use the method that is defined in SLList class?

public class SLList {

    public class IntNode {

        public int item;
        public IntNode next;

        public IntNode(int i, IntNode n) {
            item = i;
            next = n;
        }
    }

    private IntNode first;

    public SLList(int x) {
        first = new IntNode(x, null);
    }

    public int size() {
        if (first.next == null) {
           return 1;
        }
        return 1 + first.next.size();
    }
}

I am just new to Java, and quite confused about the private and static things, especially when it comes to the Class. Thank you for anyone answering me.


Solution

  • You can fiddle it by adding an extra private method but it's not particularly easy to reason about. I would avoid doing it this way unless absolutely necessary.

    class SLList {
    
        public class IntNode {
    
            public int item;
            public IntNode next;
    
            public IntNode(int i, IntNode n) {
                item = i;
                next = n;
            }
    
            private int theSize()
            {
                return size();
            }
        }
    
        private IntNode first;
    
        public SLList(int x) {
            first = new IntNode(x, null);
        }
    
        public int size() {
            if (first.next == null) {
                return 1;
            }
            return 1 + first.next.theSize();
        }
    }