GreenOwl
GreenOwl

Reputation: 765

How to define a inner class with static value and make it can access outer class object

I want to define a class like this:

class Tree{
    ArrayList<Node> nodes;
    //...
    class Node{
        static int n = 0;
        private int id;
        public Node(){
            id = n++;
            Tree.this.nodes.add(this);
        }
    }
}

It seems like that if I define static int n = 0, Node must be static. When I add static on Node, Tree.this doesn't work. What should I do?

Upvotes: 0

Views: 69

Answers (1)

Manjunath
Manjunath

Reputation: 1685

You can try this if it meets your needs:-

class Tree{
    ArrayList<Node> nodes;
    private static int n = 0;
    //...
    class Node{
        private int id;
        public Node(){
            id = n++;
            Tree.this.nodes.add(this);
        }
    }
}

Upvotes: 3

Related Questions