【问题标题】:Does it matter if a private nested class is static or not?私有嵌套类是否是静态的有关系吗?
【发布时间】:2020-02-16 06:08:12
【问题描述】:

我有点困惑。在阅读 java 教程时,一个问题对我来说是“唤醒”。如果我决定嵌套类需要使用私有访问修饰符,那么嵌套类是否为静态是否重要(根本)? 最初我认为这无关紧要,但在编写了一些类以验证我的直觉之后,我发现在使用和不使用“static”关键字运行程序时会出现一些不同的“结果”。

以下代码无法编译,得到如下编译错误:“non static method callByInnerClass() cannot be referenced from a static context”

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();
        }

    }
}

当删除内部类之前的“static”关键字时,程序编译成功。当“static”关键字存在时,嵌套类找不到他的外部类实例(并被认为是内部)的原因是什么? 我读到,当从不同的类创建内部类的对象时,内部类自动具有外部类实例,但这种情况感觉有点不同

【问题讨论】:

  • 是的,这很重要。如果嵌套类不是静态的,则需要创建包含类的实例。它还会影响变量范围/可见性
  • 让我们从基础开始。你熟悉static 关键字在 Java 中的含义吗?将字段和方法等成员设为静态与非静态有什么区别?
  • @Pshemo,是的,我是。静态键意味着变量/方法属于类而不是类的实例
  • 是的,换句话说,在static 方法中没有this(它指的是实例调用哪个方法)但它存在于非静态方法中这允许我们编写类似void foo(){ this.bar(); } 甚至void foo(){ bar(); } 的代码(这里this. 之前的bar() 将由编译器生成)。类似地,静态和非静态嵌套类型不同,但在它们的情况下,非静态嵌套类有 this$0 隐藏变量,它保存对创建非静态类的外部类 instance 的引用以及我们何时写outerMethod()编译器会生成this$0.outerMethod()
  • 静态嵌套类的实例不是通过outerClassInstance.new StaticNestedClass();这样的外部实例创建的,因此它们没有这样的this$0,这意味着编译器将无法在内部进行更改他们nonStaticOuterMethod() 变成this$0.nonStaticOuterMethod()。更多信息:What does it mean if a variable has the name “this$0” in IntelliJ IDEA while debugging Java?.

标签: java private inner-classes


【解决方案1】:

您不能从静态类访问您的非静态calledByInnerClass 方法。这就是它给出错误的原因。为此,您需要将 calledByInnerClass 设为静态或您的内部类为非静态

【讨论】:

    猜你喜欢
    • 2011-12-25
    • 2014-08-30
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多