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
}
}
Foo is a member of
ClassHierarchyTest1
. Hence you have to useClassHierarchyTest1
inorder to access it's members.Docs of Inner Classes
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
add static to your class
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.
Foo
is an inner class and therefore you can access it only through instance ofClassHierarchyTest1
. Like that:Another option is to define
foo
as static: