我有,如何實現一個內部類?
我有這樣的場景:
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的實例。我可以對我提到的選項做同樣的事情嗎?
+1添加'private'是我在其他方面很好的「選項1」實現中唯一改變的。 – dasblinkenlight
謝謝。實際上,我將在D之外創建A,B和C的實例。總之,我希望將所有類都放在一個java文件中,但是它們的行爲就像在不同的java文件中一樣。 – sosegon12
@sosegon - 如果是這種情況,您應該避免它,將它們分隔到不同的文件中,這樣會更好,更清晰,更易於維護。 – MByD