Udostępnij za pośrednictwem


Abstract Class or Interface II

In previous post, I was convinced that abstract class was the right choice for the work I am doing. However, when I got deeper into the work, I had to switch to use interface simply because abstract class does not support multiple inheritance.

I am creating a hierarchy of pure abstract classes to be accessed by user and another hierarchy of classes having the implementation. For example,

     public abstract class Foo
    {
        public abstract void Bar();
    }

    public abstract class SubFoo : Foo
    {
        public abstract void Baz();
    }

    public class FooImpl : Foo
    {
        public override void Bar()
        {
            // implementation
        }
    }

Now if I try to create a class like:

     public class SubFooImpl : SubFoo, FooImpl
    {
        public void Baz()
        {
            // implementation
        }
    }

I get syntax error because SubFooImpl cannot inherit from both Foo and FooImpl. The problem here is that SubFooImpl needs to assume the identity of SubFoo and also borrows implementation from FooImpl. You can only use interface in this case. The code will be like:

     public interface IFoo
    {
        void Bar();
    }

    public interface ISubFoo : IFoo
    {
        void Baz();
    }

    public class FooImpl : IFoo
    {
        public void Bar()
        {
            // implementation
        }
    }

    public class SubFooImpl : FooImpl, ISubFoo
    {
        public void Baz()
        {
            // implementation
        }
    }

This is an example that guidelines of programming is not something we can blindly follow. Without understanding the reasoning and context, they can still lead to the wrong choice.

Keywords: .Net, abstract class, interface

Comments