theateist
theateist

Reputation: 14399

Why I get error "non-static variable this cannot be referenced from a static context"?

I've read about non-static variable this cannot be referenced from a static context error but I don't understand why I get it in my case (line return new CommandParser1(command);)?. I just create instance of class. That's all. What is the problem?

public class ProtocolUtility {

    public static CommandParser createParser(String command) throws Exception {           
        switch (command) {
            case COMMAND_1:
                return new CommandParser1(command);                  
            case COMMAND_2:
               return new CommandParser2(command);
            default:
                return null;
        }
    }

   public abstract class CommandParser {

       protected String command;

       public String getCommand() {
          return command;
       }       
   }

   public  class CommandParser1 extends CommandParser {       
       public CommandParser1 (String command){
           //...
       }       
   }

   public  class CommandParser2 extends CommandParser {      
       public CommandParser2 (String command)  {
           //...
       }      
   }

}

Upvotes: 2

Views: 708

Answers (4)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. Static method canNOT access a Non-static method or variable.

Your code return new CommandParser1(command); in inside static method public static CommandParser createParser(String command), so thats causing the error.

2. And as you are trying to access CommandParser1(command) which is an inner class from class ProtocolUtility which is its outer class, YOU CAN DIRECTLY ACCESS IT AS YOU ARE DOING IT NOW But suppose, when you are trying to make an access to it from outside the ProtocolUtility class, then you need to Create an Outer class instance to access this inner class method.

Upvotes: 0

STM
STM

Reputation: 964

Because CommandParser1() is not static. You need an instance of CommandParser1 to call CommandParser1() or to define it as static.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

CommandParser is an inner class which means it needs an instance of outer class (ProtocolUtility) to be created. Change its declaration to:

public static abstract class CommandParser {

Alternatively declare CommandParser in a separate .java file.

Your code would also work if createParser() wasn't static as in this case an instance of ProtocolUtility you are currently in would be used as an outer instance.

Upvotes: 3

Simeon Visser
Simeon Visser

Reputation: 122336

When createParser is called in a static way (i.e., ProtocolUtility.createParser(...)) you can't instantiate objects from classes that are defined inside ProtocolUtility as that would require you to have an instance of that class (which you don't have). This can be fixed by also making the inner classes static.

Upvotes: 1

Related Questions