OOP: DilemmaPosted: June 25, 2004
Class B, inherits from Class A… Assuming, we are in the Java environment, Constructor of class B implicitly invokes constructor of Class A before any lines of code are executed in Class B. Class A depends on an abstract method (or a virtual method for C++) implemented by inheriting sub-class B. The dependancy is such that the method, say ‘P’, is called in the Constructor of class A. The particular method P, in turn, depends on Class C, which cannot be initialized until and unless Class B’s constructor returns control to Class A’s constructor.
Trouble is: the usual Chicken and Egg Dilemma! It’s a circular dependancy, in other words.
Have class B implement an abstract method ‘Q’ that acts like a constructor that is called by Class A before it attempts to call method P. the method ‘Q’ can then initialize Class C through having class A’s constructor call method ‘Q’. Then method ‘Q’ can return control to class A’s constructor which then returns to class B’s constructor.
I suspect the dependancy should not have existed in the first place! Is this a case of subtly bad design at the outset?