Java – can I instantiate an anonymous class in the constructor of an external class?
I have the following code:
public class Outer { public Interface Anony { public void callback(); } public Outer() { OtherClass.foo(new Anony() { @Override public void callback() { .... } }); } }
But my friend told me there were some problems I created an anonymous class instance in the constructor of outer, so the anonymous class instance implicitly refers to the external class instance, outer this. But at this moment, the instance of the external class has not been completely created Therefore, anonymous class instances refer to an object with incomplete state, so this problem
Is he right? Thank you
Solution
Your friend is right, but it depends on the usage of course
The problem is not creating inner classes in constructors If an inner class accesses an outer class, a problem occurs
This is because any object will not be able to give a normal acceptor in the constructor All variables required for object operation may not have been initialized, etc
However, if the inner class is placed at the end of the constructor, I don't see this problem happen, but remember, this is a dangerous game because someone may modify the code, and then it is equivalent to the time of the debugger