Interface implementation and common function

I have the following requirement,

  • There will be 2(or more) different classes to perform same kind of operation(in different ways). Therefore I decided to create an interface. Then I implemented these 2 classes with my interface.
  • Now, from another class I will be using the object of type Interface and calls functions. Everything works fine.
  • Then a new requirement came to create a common functionality that applies to both classes.
  • I don't want to define same function in both classes. And interface dont allows function definition.
  • First I thought abstract class will be useful. Because it allows function definition and abstract functions. But abstract classes cant be instantiated and also I need to create objects with individual class types.

Sorry I cant find a simple way to define my problem. It feels like a solution that spring framework provides. But I need to know how to acheive this from a Java/C# application.

Jon Skeet
people
quotationmark

It sounds like you want an abstract class implementing the common functionality, but still have two concrete classes for the distinct functionality. You may or may not still want to keep the interface as well. So the options are:

        Interface
            ^
            |
         Abstract
          class
            ^
           / \
   Concrete   Concrete 
   class 1    class 2

or just

         Abstract
          class
            ^
           / \
   Concrete   Concrete 
   class 1    class 2

Code which wants to use these classes just uses the interface or abstract class. How you configure which concrete class to use were will depend on your exact requirements - but presumably you'd already tackled that in the earlier version.

people

See more on this question at Stackoverflow