Why do I get “non-static variable this cannot be referenced from a static context”?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 17:54:16

Your nested class (which isn't a subclass, by the way) isn't marked as being static, therefore it's an inner class which requires an instance of the encoding class (JavaApp1) in order to construct it.

Options:

  • Make the nested class static
  • Make it not an inner class (i.e. not within JavaApp1 at all)
  • Create an instance of JavaApp1 as the "enclosing instance":

    GenTest x = new JavaApp1().new GenTest();
    

Personally I'd go with the second approach - nested classes in Java have a few oddities around them, so I'd use top-level classes unless you have a good reason to make it nested. (The final option is particularly messy, IMO.)

See section 8.1.3 of the JLS for more information about inner classes.

It should be static class GenTest, as you create an instance of it from static method.

Also, in general, inner classes should be static.

The class GenTest is a non-static class and therefore must be instantiated within an instance of JavaApp1. If you do static class GenTest what you have work otherwise you need to create an instance of JavaApp1 and create the GenTest within a non-static method.

Thar's because GenTest is defined withing the context of JavaApp1. So you can refer to it unless you have an instance of JavaApp1. Change it to a static class for it to work.

static class GenTest...

Please Use

static class GenTest()......
Siddharth Singh

The way you are invoking isn't the correct way to do that. Since the inner class GenTest is a member of the JavaApp1 the correct way to invoke it would be

GenTest x = new JavaApp1().new GenTest();

Using it your class would compile correctly.

The class is nested which means that your nested class is not static, which means you have to create an object for the nested class through the object of the main class. what that means is your psvm should be like this.

public static void main(String[] args) {
    JavaApp1 a=new JavaApp1(); //create an object for the main class
    JavaApp1.GenTest x=a.new GenTest();

    x.oldFunction();
    x.newFunction();
}
class Test {

    static class GenTest { // nested class with static

        static void oldFunction() { // static method
            System.out.println("don't use that");
        }
        void newFunction() { // non-static method
            System.out.println("That's ok.");
        }
    }

    public static void main (String[] args) {
        GenTest.oldFunction(); // call static method

        GenTest two = new GenTest(); // call non-static method
        two.newFunction();
    }

}

Java Online java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!