C # Interface class + inheritance VS pure Abstract class

Is this OOP approach doomed to fail or is there some merit in it?

Before I understood abstract classes, I was getting more or less the same benefits of code reuse by using an interface class + a regular class that implements certain interface methods. for example

public interface IMyService
{
    String Helloword1();
    String Helloword2();
    String Helloword3();
}

public class MyService
{
    public String Helloword1(){return "1";}
    public String Helloword2(){return "2";}
    //Helloworld3 is not here so I would be forced to provide implementation in any subclass
    //very similar to calling abstract on a method
}



public class SubClass1: MyService, IMyService
{

    public String Helloword3(){return "3";}

}


public class SubClass2: MyService, IMyService
{

    public new String Helloword2(){return "override method";}
    public String Helloword3(){return "3";}

}

      

Can anyone see any advantage of this or does it really provide the same benefits as an abstract class?

+3


source to share


2 answers


Can anyone see any advantage of this or does it really provide the same benefits as an abstract class?

There is a big disadvantage to this. You are allowing people to subclass MyService

without implementation Helloword3

, since this is not part of the contract.



The abstract class will use the fact that the type implements this element. This is where you trust that the user will execute the "required" interface.

+2


source


In your example, someone can actually construct an instance MyService

and use it without using an abstract method.

Honestly, there isn't even a need to inherit the form MyService

in your two subclasses. If MyService

it can be instantiated in a specific way, this type can be composed rather than inherited from.

The real meaning in an abstract class is where the concrete methods actually use the abstract methods. Ability to write things like this:



public abstract class Foo
{
    public abstract Guid CreateUniqueIdentifier();
    public void SaveToDatabase()
    {
        Guid guid = CreateUniqueIdentifier();
        //do stuff with guid
    }
}

      

You cannot do something like this using your template; concrete methods can never depend on methods not yet implemented.

+2


source







All Articles