views:

87

answers:

3
interface ICanvasTool
{
    void Motion(Point newLocation);
    void Tick();
}

abstract class CanvasTool_BaseDraw : ICanvasTool
{
    protected abstract void PaintAt(Point location);

    public override void Motion(Point newLocation)
    {
        // implementation
    }
}

class CanvasTool_Spray : CanvasTool_BaseDraw
{
    protected abstract void PaintAt(Point location)
    {
        // implementation
    }

    public override void Tick()
    {
        // implementation
    }
}

This doesn't compile. I could add an abstract method "Tick_Implementation" to CanvasTool_BaseDraw, then implement ICanvasTool.Tick in CanvasTool_BaseDraw with a one-liner that just calls Tick_Implementation. Is this the recommended workaround?

+4  A: 

The way to do this is to add an abstract void Tick() method to CanvasTool_BaseDraw and override it in CanvasTool_Spray.

Not every programming language does it this way. In Java you do not have to add an abstract method for every method in the interface(s) you implement. In that case your code would compile.

Ronald Wildenberg
Thanks. Seems a bit counter intuitive, but it does work.
Stefan Monov
+3  A: 

You have a few things mixed up..

Motion should be virtual in your base class so that it may be overridden in child classes. Your child class needs to make PaintAt override instead of abstract. The base class needs to implement Tick as an abstract method.

interface ICanvasTool
{
    void Motion(Point newLocation);
    void Tick();
}

abstract class CanvasTool_BaseDraw : ICanvasTool
{
    protected abstract void PaintAt(Point location);

    public virtual void Motion(Point newLocation)
    {
        // implementation
    }

    public abstract void Tick();
}

class CanvasTool_Spray : CanvasTool_BaseDraw
{
    protected override void PaintAt(Point location)
    {
        // implementation
    }

    public override void Tick()
    {
        // implementation
    }
}
Krisc
Yeah, the first two mistakes were the result of impatiently rushing a code-example for SO. And your solution is correct. Thanks.
Stefan Monov
Er, hold on. Why does Motion need to be virtual in CanvasTool_BaseDraw? I don't really need to allow subclasses to override it.
Stefan Monov
I apologize. It doesn't _have_ to be. I just assumed that you wanted it to be overridable since it was a base class.However, using 'override' there is illegal since you are implementing an interface, not inheriting an abstract class or class with a virtual method.
Krisc
True again. Thanks.
Stefan Monov
A: 

As was stated before, an interface is a contract and therefore all of it needs to be implemented. If a a consumer tried to call something that is defined in the interface but not implemented in the concrete class the application would crash.

George Handlin
Yes, but CanvasTool_BaseDraw is *not* a concrete class.
Stefan Monov