2012-05-16 55 views
3

我有,如何實現一個內部類?

我有這樣的場景:

public class A{ 
    //attributes and methods 
} 

public class B{ 
    //attributes and methods 

} 

public class C{ 
    private B b; 
    //other attributes and methods 
} 

public class D{ 
    private C c1, c2, c3; 
    private List<A> a; 
    //other attributes and methods 
} 

每個類都有自己的文件。不過,我想把A,B和C的類作爲D類的內部類,因爲我沒有在整個程序中使用它們,只是在它的一小部分中使用它們。我應該如何實施它們?我讀過它,但我仍然不知道什麼是最好的選擇:

選項1,使用靜態類:

public class D{ 
    static class A{ 
    //attributes and methods 
    } 

    static class B{ 
    //attributes and methods 
    } 

    static class C{ 
    private B b; 
    //other attributes and methods 
    } 

    private C c1, c2, c3; 
    private List<A> a; 
    //other attributes and methods 
} 

選項2,使用一個接口和一個類實現它。

public interface D{ 
    class A{ 
    //attributes and methods 
    } 

    class B{ 
    //attributes and methods 
    } 

    class C{ 
    private B b; 
    //other attributes and methods 
    } 

} 

public class Dimpl implements D{ 
    private C c1, c2, c3; 
    private List<A> a; 
    //other attributes and methods 
} 

我想知道哪種方法更好,以獲得使用原始場景相同的行爲。如果我使用選項1並使用這樣的類,它可以嗎?

public method(){ 
    List<D.A> list_A = new ArrayList<D.A>(); 
    D.B obj_B = new D.B(); 
    D.C obj_C1 = new D.C(obj_B); 
    D.C obj_C2 = new D.C(obj_B); 
    D.C obj_C3 = new D.C(obj_B); 

    D obj_D = new D(obj_C1, obj_C2, obj_C3, list_A); 
} 

基本上,我關心的是如何創建內部類將影響外部類。在最初的場景中,我首先創建類A,B和C的實例,然後創建類D的實例。我可以對我提到的選項做同樣的事情嗎?

回答

6

如果你只打算在課堂上使用它們,你沒有理由使用接口,因爲接口的目的是爲了訪問public。用你的第一種方法(並使類私人靜態)

+0

+1添加'private'是我在其他方面很好的「選項1」實現中唯一改變的。 – dasblinkenlight

+0

謝謝。實際上,我將在D之外創建A,B和C的實例。總之,我希望將所有類都放在一個java文件中,但是它們的行爲就像在不同的java文件中一樣。 – sosegon12

+0

@sosegon - 如果是這種情況,您應該避免它,將它們分隔到不同的文件中,這樣會更好,更清晰,更易於維護。 – MByD

0

內部類的2種類型:

  1. 靜態內部類(被稱爲頂級類)

  2. 內部類

Static Inner Class示例:

public class A { 

       static int x = 5; 

       int y = 10; 


       static class B { 

       A a = new A();  // Needed to access the non static Outer class data 

       System.out.println(a.y); 

       System.out.println(x); // No object of outer class is needed to access static memeber of the Outer class 

    } 

}

嵌套類實例:

  public class A { 

         int x = 10; 

        public class B{ 

         int x = 5; 

       System.out.println(this.x); 
       System.out.println(A.this.x); // Inner classes have implicit reference to the outer class 

       } 
      } 

要創建內部類(不是靜態內部類)的objec,從外部,需要外部類objec首先被創建。

A a = new A();

A.B b = a.new B();