Nested Static classes Java [duplicate]

旧巷老猫 提交于 2020-01-16 09:06:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!