strange Cannot be referenced from a static context

2020-07-30 06:08发布

Wondering - why there is such error message during compile:

ClassHierarchyTest1.this Cannot be referenced from a static context

Source code:

public class ClassHierarchyTest1 {
    class Foo {
        int a;
        Foo(int b) {
            this.a = b;
        }
    }

    public static void main(String[] args) {
        Foo f = new Foo(1); // this line has the error message
    }
}

标签: java
4条回答
Rolldiameter
2楼-- · 2020-07-30 06:52

Foo is a member of ClassHierarchyTest1 . Hence you have to use ClassHierarchyTest1 inorder to access it's members.

Docs of Inner Classes

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();
查看更多
够拽才男人
3楼-- · 2020-07-30 06:54

add static to your class

public class ClassHierarchyTest1 {

class static Foo {
    int a;
    Foo(int b) {
        this.a = b;
    }
}

public static void main(String[] args) {
    Foo f = new Foo(1); // this line has the error message
}
}
查看更多
对你真心纯属浪费
4楼-- · 2020-07-30 07:00

Not at all strange.

Your inner class itself is not static. Thus it always needs an object of the outer enclosing class. Which you don't have in your static main.

So you have to change Foo to be static (of course you then can't use the "outer this"), or you have to create an instance of your outer class first,and call new on that object.

查看更多
SAY GOODBYE
5楼-- · 2020-07-30 07:01

Foo is an inner class and therefore you can access it only through instance of ClassHierarchyTest1. Like that:

 Foo f = new ClassHierarchyTest1().new Foo(1);

Another option is to define foo as static:

static class Foo{...}
查看更多
登录 后发表回答