dushkin
dushkin

Reputation: 2101

Handling nested classes

I am having difficulties to handle the following classes gracefully:

Suppose I have the following class A:

class A{

  B b1;

  class B{

    C c1;
    D d1;

    class C{
    .
    .
    .
    }

    class D{
    .
    .
    .
    }

  }
}

and I have also class AA:

class AA{

  B b1;

  class B{

    C c1;
    E e1;

    class C{
    .
    .
    .
    }

    class E{
    .
    .
    .
    }

  }
}

I need to create and initialize objects of A or AA depending on some flag state. Notice that class B inside class A is nesting class D whereas class B inside class AA is nesting class E !

The automatic thought I had is to derive them from some base class and use a factory. Then I would get an object which I can use, but then I would face the need to work with D or E objects. But I don't know exactly how to implement this idea. Is it possible at all? Is there a better way of achieving it?

Thank you!

Upvotes: 0

Views: 40

Answers (2)

jean
jean

Reputation: 4350

If you need to nest classes that way first revise your design. If you really want to stick with it you can just create a property object and let programmatically (a factory?) instantiate the right ones.

class B{

   C c1;
   // ...

   // possible a D & E parent class
   Object X;
}

class A
  B b1;
  // ...
}

depending on your needs you can combine generics and/or constructors in a way instatianting A can lead to conditional instantiation of (the correct B). In this scenario leting all this logic in a factory makes sense IMHO

Upvotes: 1

biziclop
biziclop

Reputation: 49724

In general, I'd try to avoid multiple levels of inner classes, as it often creates awfully complicated code.

In your example, since A and AA have a field of type B, eliminating the need for an inner class is easy:

class Bar {
   Foo foo;

   static class Foo { // this is just a nested class now, it can easily be moved to top level
       private Bar parent;
   }

   void setFoo(Foo foo) {
      this.foo = foo;
      foo.parent = this;
   }
}

(The above is just a simplified example to show the mechanism, in real code you should make additional checks, i.e. foo != null and what should happen if foo.parent is already set to a non-null value)

The situation is slightly different if both A and B are immutable, in that case instantiation of B has to be strictly controlled by A.

Upvotes: 1

Related Questions