2013-07-07 71 views
2

我讀有效的Java 2 - 第22項,並在標題中說:靜態和非靜態內部類的區別?

「在非靜態的青睞靜態成員類」,但在本章結尾

集合接口,如Set和List的

實現, 通常使用非靜態成員類來實現自己的迭代器:

// Typical use of a nonstatic member class 
public class MySet<E> extends AbstractSet<E> { 
    ... // Bulk of the class omitted 

    public Iterator<E> iterator() { 
     return new MyIterator(); 
    } 

    private class MyIterator implements Iterator<E> { 
     ... 
    } 
} 

我做了一個測試程序,看看它們之間是否有任何區別。

public class JavaApplication7 { 


    public static void main(String[] args) { 
     // TODO code application logic here 
     JavaApplication7 t = new JavaApplication7(); 

     Inner nonStaticObject = t.getAClass(); 
     Sinner staticObject = new JavaApplication7.Sinner(); 

     nonStaticObject.testIt(); 
     staticObject.testIt();   
    } 

    public Inner getAClass(){ 
     return new Inner(); 
    } 

    static class Sinner{ 
     public void testIt(){ 
      System.out.println("I am inner"); 
     } 
    } 

    class Inner{ 
     public void testIt(){ 
      System.out.println("I am inner"); 
     } 
    } 
} 

輸出是

我內心 我內心

所以,他們也做了同樣的工作。

我不知道爲什麼非靜態類在本例中使用?

回答

4

的迭代器通常需要參考使用擺在首位,以創建集合。你可以用一個靜態嵌套類來完成這個工作,它明確提供了對集合的引用 - 或者你可以使用一個內部類,它隱式地引用了這個引用。

基本上,如果嵌套類的每個實例都需要一個實例的封裝類的操作(該實例並不改變),那麼你還不如讓一個內部類。否則,使它成爲一個靜態嵌套類。

2

static與非靜態嵌套類的區別在於非靜態嵌套類與外部類的實例隱含關聯,它們可以稱爲OuterClassName.this。此引用有用實現迭代器的時候,因爲他們需要訪問它們與集合的成員。你可以通過使用一個static嵌套類來實現同樣的事情,這個嵌套類明確地將引用傳遞給外部類。

3

不同的是,非靜態內部類必須包含類的隱式引用。

public class JavaApplication7 { 

    //You can access this attribute in non-static inner class 
    private String anyAttribute; 

    public Inner getAClass(){ 
    return new Inner(); 
    } 

    static class Sinner{ 
    public void testIt(){ 
     //Here, you cannot access JavaApplication7.this 
    } 
    } 

    class Inner{ 
    public void testIt(){ 
     //Here, you can access JavaApplication7.this 
     //You can also access *anyAttribute* or call non-static method getAClass() 
    } 
    } 
} 
0

有沒有這樣的事,作爲一個靜態內部類,它是靜態的嵌套類。 「非靜態[嵌套]類的每個實例隱含地與其包含類的封閉實例相關聯......可以調用封閉實例上的方法。」

靜態嵌套類不具有訪問封閉的實例。

參考:this so thread

0
In the case of creating instance, the instance of non s 
static inner class is created with the reference of 
object of outer class in which it is defined……this 
means it have inclosing instance ……. 
But the instance of static inner class 
is created with the reference of Outer class, not with 
the reference of object of outer class…..this means it 
have not inclosing instance… 
For example…… 
class A 
{ 
class B 
{ 
// static int x; not allowed here….. 

} 
static class C 
{ 
static int x; // allowed here 
} 
} 

class Test 
{ 
public static void main(String… str) 
{ 
A o=new A(); 
A.B obj1 =o.new B();//need of inclosing instance 

A.C obj2 =new A.C(); 

// not need of reference of object of outer class…. 
} 
}