java - Why can't object of nested class be used as a parameter of supertype constructor? -


i have code following:

class {   final object data;    a(object _data) {       data = _data;   }    class b extends {       b() {           super(new c());       }        class c { }   } } 

i following error message:

cannot reference 'c' before supertype constructor has been called

i don't understand why not possible.

are there workarounds? want data final , classes nested in code above (i don't want create different file each class, because classes quite small , in real code more logical them nested)

the problem non-static inner classes need instance of outer class before can instantiated. that's why can access fields of outer class directly in inner class.

make inner classes static , should work. in general it's pattern use static inner classes instead of non-static. see joshua bloch's effective java item 22 more information.

class {    final object data;    a(final object _data) {     data = _data;   }    static class b extends {      b() {       super(new c());     }      static class c {     }   } } 

Comments