我有一个主类“m”和2个内部类叫做sub1,sub2,其中sub2是静态类:
public class m
{
String n="n";
static String s="s";
public class sub1
{
public void fn(){System.out.println(n);}
//static public void fs(){System.out.println(s);}
}
static class sub2
{
//public void fn(){System.out.println(n);}
static public void fs(){System.out.println(s);}
}
public void f()
{
sub1 s1=new sub1();//OK, no error
sub2 s2=new sub2();//OK
}
public static void main(String[] args)
{
m obj=new m();
sub1 s1=new sub1();//Error
s1.fn();
//s1.fs();
sub2 s2=new sub2();//OK
//s2.fn();
s2.fs();
}
}
我使用Openjdk在linux下编译它,它报告错误
$ java -version
openjdk version "1.8.0_91"
OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-3ubuntu1~16.04.1-b14)
OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
$ javac m.java
m.java:24: Error: Cannot reference non-static variable this in a static context.
sub1 s1=new sub1();//Error
^
1 Errors
这对我来说很奇怪: 1.在m.f()成员函数中,我们可以“sub1 s1 = new sub1();”,但在main中,我们不能 2. staic class sub2可以有实例,而非静态sub1不能吗?
这是Java的设计吗?为什么呢?
答案 0 :(得分:7)
所以你必须做这样的事情,
OuterClass outer = new OuterClass();
InnerClass inner = outer.new InnerClass();
所以,在你的情况下,
m obj = new m();
sub1 s1 = obj.new Sub1();