2013-07-07 64 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…. 
} 
}