Instantiate inner class object from current outer class object

后端 未结 3 855
梦毁少年i
梦毁少年i 2020-12-11 08:23

I am wondering if the following is valid in Java:

class OuterClass {

    OuterClass(param1, param2) {
        ...some initialization code...
    }

    void         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 09:07

    Every instance of an inner class, unless the Class is declared as static, must have a 'connected' instance of an outer class, in order to be instantiated.

    This won't work:

    public class Outer {
        public class Inner { 
        }
        public static void main(String[] args) {
            Inner inner = new Inner(); //compilation error
        }
    }
    

    However, this will work, it doesn't need an instance of Outer, since the static keyword is used:

    public class Outer {
        public static class Inner { 
        }
        public static void main(String[] args) {
            Inner inner = new Inner(); 
        }
    }
    

    more info: java inner classes

提交回复
热议问题