Why doesn’t Java allow you to create instances of inner classes?
•
Java
See English answers > 25 Java inner classes and static nested classes
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();
}
}
I use openjdk to compile it under Linux, and it reports errors
$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
This is strange to me: 1 In the m.f() member function, we can "sub1 S1 = new sub1();", But in main, we can't 2 Can static class sub2 have instances instead of static sub1?
Is this a java design? Why?
Solution
>A non - static inner class is treated as a member of an outer class
So you have to do something like this,
OuterClass outer = new OuterClass(); InnerClass inner = outer.new InnerClass();
So, in your case,
m obj = new m(); sub1 s1 = obj.new Sub1();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
