Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: Why does Java argue about making a class instance Date: Sat, 26 Mar 2016 16:04:07 -0400 Organization: A noiseless patient Spider Lines: 49 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sat, 26 Mar 2016 20:01:00 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="2d081e2f7155c28005d4472f67c2f43d"; logging-data="14787"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18dm/2XhXOhWMpvZE/BYLSd" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.7.1 In-Reply-To: Cancel-Lock: sha1:VgmN6GfVrvbU6LSBT5mc6hWX7H4= Xref: csiph.com comp.lang.java.programmer:34026 On 3/26/2016 3:44 PM, Popping mad wrote: > When I try to compile this (example from antlr4 FIWIW) > [...] > public class Main { > public static void main(String[] args) { >[...] > CollectVarsVisitor my_visitor = new CollectVarsVisitor(); > [...] > } > > public class CollectVarsVisitor extends CalcBaseVisitor { > [...] > } > [...] > it says > > [ruben@manjaro calculator]$ javac Main.java > Main.java:15: error: non-static variable this cannot be referenced from a > static context > CollectVarsVisitor my_visitor = new CollectVarsVisitor(); > ^ > 1 error > > I have no clue what is the problem, but it is not a standard static > problem CollectVarsVisitor is an "inner class," a nested class each of whose instances belongs to an instance of the containing class (Main). You cannot have a CollectVarsVisitor instance without a Main instance to own it. Since the main() method is static, there is no Main instance around to be the owner of the new CollectVarsVisitor. And that's why the compiler complains (in its ever-so-transparent way). I'm not quite sure what you're trying to do, but it looks like the solution might be to use a static nested class: public /* => */ static /* <= */ class CollectVarsVisitor ... If the nested class is truly supposed to be an inner class (belonging to a Main instance), then you'll need a Main: Main my_main = new Main(); CollectVarsVisitor my_visitor = my_main.new CollectVarsVisitor(); -- esosman@comcast-dot-net.invalid "Don't be afraid of work. Make work afraid of you." -- TLM