写了一个非常简单的例子
public class test {
public class abc {
}
public static void main (String[] args) {
...
}
}
在main函数中 申明abc的对象
abc var = new abc();
编译的时候总是报告这个错误
test.java:7: non-static variable this cannot be referenced from a static context
abc var = new abc();
^
1 error
shell returned 1
Press ENTER or type command to continue
调查类一下StackOverflow 上面有如下解释
http://stackoverflow.com/questions/15331846/non-static-variable-this-cannot-be-referenced-from-a-static-context
In Java there are two types of nested class : "Static nested class" and "Inner class" . Without the
static
keyword it is an inner class and you will need an instance of
ShowBike
to access
ShowBike.Bycicle
:
大概意思就是java的嵌套类型有两种一个事静态的一个是非静态的。因为main函数是静态的所以需要调用静态的内嵌子类。如果一定要吊用非静态的子类需要先申明一个父类的对象然后才能调用子类。
于是做了以下实验
public class test {
public static class abc {
}
public static void main(String[] args) {
abc var = new abc();
}
}
这样代码就可以编译通过.