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

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 to this 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.


你可能感兴趣的:(No enclosing instance of type SearchCommand is available due to some intermediate constructor invoca)