在Java中访问静态嵌套类的方法

时间:2016-11-29 16:08:32

标签: java inner-classes static-class

我已经了解到静态嵌套类应该像外部类的字段一样被访问(第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(){}
    }
}

1 个答案:

答案 0 :(得分: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()
    }
}