问题
I am a beginner to java. I was practicing java nested classes when I run the given problem. Oracle JDK 11.0.5
Problem:-
Whenever I try to run the compiler for the following code I run across the given errors.
public class test {
public class Outer{
static int out1;
public static void display1() {
System.out.println("\n\nIn outer one!");
System.out.println(out1);
}
public static class Inner{
static int ini;
static String ins;
static char inc;
static float inf;
static {
ini = 2;
ins = "Inner";
inc = 'I';
inf = 2.0f;
}
public static void display2() {
System.out.println("In the inner class now!");
System.out.println(ini);
System.out.println(ins);
System.out.println(inc);
System.out.println(inf);
}
}
}
public static void main(String[] args) {
Outer o1 = new Outer();
o1.Inner.display2();
}
}
Errors.jpeg
But when I add the static keyword in line-1 to make it "public static class Outer" and NO other changes, the code started working fine. Why is it? Is it because static members can't access non-static data. Please help ASAP.
回答1:
public class test {
public class Outer{
}
public static void main(String[] args) {
Outer o1 = new Outer();
Outer
requires a reference to test.this
. You would need to supply a reference to an instance of test
to the constructor with the highly obscure syntax that hopefully you will never see in real code.
There are obscure restrictions regarding static members of non-static inner classes. The details are too boring to remember. Just the other day it was mooted that this be relaxed, as if Java didn't allow you to enough silly things in this area already.
o1.Inner.display2();
As Inner
is a static nested class ol
isn't being used as an instance here. Surprisingly it is being used for its static type and could be replaced by Outer
.
My advice would be to try to avoid nested/inner/local classes and definitely avoid any mutable statics (i.e. global state).
来源:https://stackoverflow.com/questions/59689826/nested-static-classes-java