如何实现内部类?

sos*_*n12 3 java inner-classes

在这里,

我有这种情况:

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
}
Run Code Online (Sandbox Code Playgroud)

每个类都有自己的文件.但是,我想把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
}
Run Code Online (Sandbox Code Playgroud)

选项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
}
Run Code Online (Sandbox Code Playgroud)

我想知道哪种方法更好,以便使用原始方案获得相同的行为.如果我使用选项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);
}
Run Code Online (Sandbox Code Playgroud)

基本上,我关心的是内部类的创建将如何影响外部类.在原始场景中,我首先创建类A,B和C的实例,然后创建类D的实例.我可以对我提到的选项做同样的事情吗?

MBy*_*ByD 6

如果您只想在类中使用它们,则没有理由使用接口,因为接口是用于public访问的.使用您的第一种方法(并使类私有静态)