简体   繁体   English

私有嵌套 class 是否为 static 是否重要?

[英]Does it matter if a private nested class is static or not?

I'm a little bit confuse.我有点困惑。 While reading java tutorial a question "wake up" for me.在阅读 java 教程时,我有一个问题“唤醒”。 If i decided that the nested class need to be with private access modifier, does it matter (at all) if the nested class will be static or not?如果我决定嵌套的 class 需要使用私有访问修饰符,那么嵌套的 class 是否为 static 是否重要(根本)? Initially i thought it doesn't matter but after writing some classes in order to verify my intuition i found some different "results" when running the program with and without the "static" keyword.最初我认为这无关紧要,但是在编写了一些类以验证我的直觉之后,我在使用和不使用“static”关键字运行程序时发现了一些不同的“结果”。

Following code doesn't compile, get the following compilation error: "non static method callByInnerClass() cannot be referenced from a static context"以下代码无法编译,出现以下编译错误:“无法从 static 上下文引用非 static 方法 callByInnerClass()”

public class Outer
{
    private String outerString = "nnnn";
    private InnerStatic iS;
    public void createInnerClassInstance()
    {
        iS = new InnerStatic("innter"); 
    }


    public void runInnerMethod()
    {
        iS.callInnerMethod();
    }

    // if method runs it mean the inner static class can run outer methods

    public String calledByInnerClass()
    {
        System.out.println("Inner class can call Outer class non static method");
        System.out.println("nn value after ruuning inner class is: " +outerString );
    }

    public static class InnerStatic
    {
        public String innerString;

        public InnerStatic(String str)
        {
            innerString = str;
        }

        public void callInnerMethod()
        {
            System.out.println(innerString);
            outerString  = "aaa";
            calledByInnerClass();
        }

    }
}

When removing "static" keyword before inner class, then program is compiled successfully.当去除内部 class 之前的“static”关键字时,程序编译成功。 What is the reason that when "static" keyword exist, than the nested class can't find his outer class instance (and considered inner)?当“静态”关键字存在时,嵌套的 class 找不到他的外部 class 实例(并被认为是内部)的原因是什么? I read that when creating from different class an object of inner class, then inner class automatically has outer class instance, but this situation feels a little bit different I read that when creating from different class an object of inner class, then inner class automatically has outer class instance, but this situation feels a little bit different

You cannot access your non-static calledByInnerClass method from static class.您无法从 static class 访问非静态的calledByInnerClass方法。 That is why it gives an error.这就是它给出错误的原因。 To do so, you need either make calledByInnerClass static or your inner class non-static为此,您需要将calledByInnerClass static 或您的内部 class 设为非静态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM