Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m strugging to know when to use a base class with Polymorphism or an interfac

ID: 644302 • Letter: I

Question

I'm strugging to know when to use a base class with Polymorphism or an interface.

Providing my object exposes DoThis() then I can't see why it matters if it's an interface of a base class.

Please consider the following

public void MyMethod()
{
    var myObject = new MyObject();
    myObject.DoThis();
}
In regards to MyObject, I could have created it in 2 ways

Approach 1

public class MyObject : IMyInterface
{
    public void DoThis()
    {
        //logic
    }
}
Approach 2

public class MyObject : MyBaseObject
{
    public override void DoThis()
    {
        //logic
    }
}
From what I can see, both of these implementations achieve the same thing.

The issue could be my example is too simple/contrived but, is there a way to know when to use one approach over the other? In my example above, I would guess the answer is preference? I've not done any big projects before and so I'm guessing that one isn't as extendible but I don't know why I think that!

Explanation / Answer

A base class will allow you to share mutual functionality. In your example, there is not a huge difference. However imagine you have more than one method on your class.

public abstract class MyBaseClass
{
public virtual void DoThat()
{
//do something cool
}

public abstract void DoThis();
}
If you had implemented this on a concrete using an interface, not an abstract class, then you would have to have written the functionality for both methods.

If you use an abstract class or inherit from another class then you only need to write the code for DoThis().

DoThat() already does something cool, there is no reason to rewrite it on every concrete implementation. As it's virtual though, if you need to override it then you can.