No enclosing instance of type SearchCommand is available due to some intermediate constructor invoca

来源:互联网 发布:金华亿途网络 编辑:程序博客网 时间:2024/06/12 04:06
public class SearchCommand extends Command {
    
    private static final String ACTION = "search";
    public SearchCommand() {
        this(ACTION, new SearchCommandHandler());//error: No enclosing instance of type SearchCommand is available due to some intermediate constructor invocation
    }

    public SearchCommand(String action, CommandHandler handler) {
        super(action, handler);
    }
    
    class SearchCommandHandler implements CommandHandler {
        @Override
        public void execute(PrintStream out, Properties args) {
            out.println(args.toString());
        }
        
    }

}


原因:

http://stackoverflow.com/questions/2741066/why-does-a-sub-class-class-of-a-class-have-to-be-static-in-order-to-initialize-t


Basically an inner class (without the static modifier) has an implicit reference to an instance of its outer class, so it can't be created until the outer class is created. By creating one on the call tothis it can't reference the outer class yet because the outer class isn't constructed much at all until after the call to super. The case that works for you, the assignment to head happens after the (implicit) call to super so the class is constructed enough to get a reference to it.