2016-11-29 143 views
0

我已經知道靜態嵌套類應該像外層類(第2行)一樣被訪問。但即使實例化內部類直接工作(第1行)。你能幫我理解嗎?在Java中訪問靜態嵌套類的方法

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

無關,但請考慮正常化您的縮進。無論如何,你從包含類中訪問它,所以不需要用'OuterClass'作爲前綴。這是當你從外部訪問暴露的內部類時需要包含的類。 –

+0

也無關:「報告()」應該是「報告」 – Addi

+0

@Addi我不明白。新的Report()會調用report類的默認構造函數來創建一個實例嗎? –

回答

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