How to implement an inner class?

I am there,

I have a scenario like this:

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
}

Each class has its own file. However, I would like to get classes A, B and C as inner classes of class D, because I do not use them in the whole program, just in a small part. How do I implement them? I read about this, but I'm still not sure what is the best alternative:

Option 1 using static classes:

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
}

Option 2 using an interface and a class that implements it.

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
}

I would like to know which approach is better to get the same behavior using the original script. Is it ok if I use Option 1 and use classes like this?

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

, , outter. A, B C, D. , ?

+3
2

, , public. ( private)

+6

2 :

  • ( )

:

   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

              }
          }

Inner Class ( -), , .

A a = A();

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

0

All Articles