Path: csiph.com!aioe.org!.POSTED!not-for-mail From: =?UTF-8?Q?Arne_Vajh=c3=b8j?= Newsgroups: comp.lang.java.programmer Subject: Re: Why does Java argue about making a class instance Date: Mon, 28 Mar 2016 10:10:12 -0400 Organization: Aioe.org NNTP Server Lines: 95 Message-ID: References: NNTP-Posting-Host: ANasIS7Js9OyLQwgloeBLQ.user.gioia.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.7.1 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:34041 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 Other have already pointed out the problem. But let me try and elaborate. Or maybe add to the confusion. :-) When a class is declared inside another class with static then it is just another class with an unusual name and more complex accessibility. Example: public class Main1 { // note static public static class Foobar { @Override public String toString() { return super.toString(); } } public void test() { // full syntax Main1.Foobar a = new Main1.Foobar(); System.out.println(a); // abbreviated syntax Foobar b = new Foobar(); System.out.println(b); } public static void main(String[] args) { Main1 o = new Main1(); o.test(); } } When it is declared without static, then each instance belong to an instance of the outer class. And in fact code can refer to that using classname.this syntax. Example: public class Main2 { // note not static public class Foobar { @Override public String toString() { return super.toString() + "/" + Main2.this.toString(); } } public void test() { // full syntax Main2.Foobar a = this.new Foobar(); System.out.println(a); // abbreviated syntax Foobar b = new Foobar(); System.out.println(b); } public static void main(String[] args) { Main2 o = new Main2(); o.test(); } } (and your problem as pointed out by several other was that you had this case and were using the abbreviated syntax with an implicit this prefix on new - an getting the error because in the static main there is no this) Arne