My abstract class implements the interface, but does not implement some of its methods. How do I compile it?
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
}
}
It doesn't compile. I could add the abstract method "Tick_Implementation" to CanvasTool_BaseDraw and then implement it ICanvasTool.Tick
in CanvasTool_BaseDraw
a one-liner that simply calls Tick_Implementation. Is this the recommended solution?
a source to share
The way to do this is to add an abstract method void Tick()
to CanvasTool_BaseDraw
and override it in CanvasTool_Spray
.
Not every programming language does it this way. In Java, you don't need to add an abstract method for every method in the interface (s) that you implement. In this case, your code will compile.
a source to share
You have something messed up.
The movement must be virtual in your base class so that it can be overridden in child classes. Your child class should make PaintAt an override instead of an abstract one. The base class must 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
}
}
a source to share
The alternative is not to enumerate the interface in the base class declaration. Each derived class must render ICanvasTool in its declaration if it wants to implement the interface, and then it is solely responsible for implementing the rest of the interface. One drawback I see is that you cannot explicitly implement interface methods in the base class (i.e. no ICanvasTool: Motion), but otherwise this is a pretty low overhead version.
public interface ICanvasTool
{
void Motion(Point newLocation);
void Tick();
}
public abstract class CanvasTool_BaseDraw
{
public void Motion(Point newLocation)
{
//some implementation
}
}
public class CanvasTool_Spray : CanvasTool_BaseDraw, ICanvasTool
{
public void Tick()
{
//some implementation
}
}
Note. I left PaintAt because it was not necessary for the example.
a source to share