【问题标题】:Ways of accessing a static nested class in Java在 Java 中访问静态嵌套类的方法
【发布时间】:2017-04-13 17:15:54
【问题描述】:

我了解到静态嵌套类应该像外部类的字段一样访问(第 2 行)。但即使直接实例化内部类(第 1 行)。你能帮我理解吗?

public class OuterClass
{
    public OuterClass() 
    {
        Report rp = new Report(); // line 1
        OuterClass.Report rp1 = new OuterClass.Report();  // line 2 
    }

    protected static class Report()
    {
        public Report(){}
    }
}

【问题讨论】:

  • 不相关,但请考虑规范化缩进。在任何情况下,您都是从包含类内部访问它,因此无需在其前面加上 OuterClass。当您从外部包含您需要限定它的包含类访问公开的内部类时。
  • 也不相关:“Report()”应该是“Report”
  • @Addi 我不明白。 new Report() 会调用报表类的默认构造函数来创建实例对吗?

标签: java inner-classes static-class


【解决方案1】:

像外部类的字段一样访问

这就是你正在做的事情。想象一下:

class OuterClass
{
    SomeType somefield;
    static SomeType staticField;     

    public OuterClass()
    {
        //works just fine.
        somefield = new SomeType();
        //also works. I recommend using this
        this.somefield = new SomeType();

        //the same goes for static members
        //the "OuterClass." in this case serves the same purpose as "this." only in a static context
        staticField = new SomeType();
        OuterClass.staticField = new SomeType()
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 2021-04-28
    • 2018-12-17
    • 2018-01-27
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多