简体   繁体   中英

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?

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM