如何实现内部类?

时间:2012-05-16 17:17:54

标签: 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
}

每个班级都有自己的档案。但是,我想把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的实例。我可以对我提到的选项做同样的事情吗?

2 个答案:

答案 0 :(得分:6)

如果您只是在课堂内使用它们,则没有理由使用界面,因为界面用于public访问。使用您的第一种方法(并使类私有静态)

答案 1 :(得分:0)

内部类有两种类型:

  1. 静态内部类(称为顶级类)

  2. 内部课程

  3. 静态内部类示例:

       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
    
                  }
              }
    

    要从外部创建内部类(NOT STATIC INNER CLASS)的目标,需要首先创建外部类目标。

    a a = new A();

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