Cleaner way of using inheritance to separate 'static' code from 'dynamic' code
<p>(With static and dynamic I mean the distinction whether code is susceptible to change)</p>

<p>I have a bit of a weird problem I'm currently stuck on. I'm writing an application which involves some complex interactions between components in which it becomes hard to keep track of the code flow. To simplify this, I'm trying to structure the code by creating 'layers', where each layer has increased functionality compared to the layer above it. Each layer is contained in a package. I'm having the following problem:</p>

<p>Consider the following 2 classes and their subclasses with increased functionality:</p>

<p>Class A:</p>

<pre><code>package layer;
class A {
    B b;

    A() {
        b = new B();
    }

    void foo() {
        b.foo();
    }

    /* More A-class methods here */
}
</code></pre>

<p>Class B:</p>

<pre><code>package layer;
class B {
    void foo() {
        // Do something
    }

    /* More B-class methods here */
}
</code></pre>

<p>Subclass A:</p>

<pre><code>package sublayer;
class ASub extends A {

    ASub() {
        super.b = new BSub(); // This needs a cast to compile
    }
}
</code></pre>

<p>Subclass B:</p>

<pre><code>package sublayer;
class BSub extends B {
     @Override
     void foo() {
        // Do something with more functionality
     }
}
</code></pre>

<p>In the end I just want to instantiate and modify classes ASub and BSub, being able to use all methods of superclasses A and B without actually needing to modify code in classes A and B itself.</p>

<p>If I call <code>new ASub().foo()</code>, I want the overridden foo() of BSub to execute instead of that of B. Ofcourse I can add a variable <code>BSub bsub</code> in ASub and override A's foo() method to call <code>bsub.foo()</code>, but this doesnt avoid the creation of the object <code>b</code> in the constructor of A, which seems sloppy coding. Any thoughts on this? Any comments are welcome.</p>