Suppose that we have the following interface:

Fig. 1: Insertable interface

Further, BaseInsert is an implementation of the Insertable<Number> interface. BaseInsert is open . So, we can extend BaseInsert .

We want CountingInsert to extend BaseInsert . Each time the code inserts a Number , the code must increase the variable count by one. So, we have:

Fig. 2: count algorithm implemented through inheritance

This implementation ought to work. Line 8 increases count by one; line 13 by the number of variable arguments.

The code does not work as expected. See line 7 of Fig. 3 below.

Fig 3. CountingInsert() produces wrong result

The problem is at line 10 of Fig. 4 below:

Fig. 4: Implementation of BaseInsert

The BaseInsert.insertAll function is a convenience function. The insertAll function calls insert for each item in the vararg list. The CountingInsert class double counted the insertion of integers 3 and 4. CountingInsert.insertAll executed the statement count++ twice; the statement count += items.size once. The CountingInsert.insertAll function increased count by four instead of two.

Are there any alternatives? Yes. We can change the code, or we can use composition.