简体   繁体   中英

When do I really need to use Abstract Methods?

If I'm writing a program that draws shapes.

abstract class GraphicObject {

    abstract void draw();
    abstract void resize();
}

and then a sub class that extends GraphicObject called Circle.

class Circle : GraphicObject {
    void draw() {
    ...
    }
    void resize() {
        ...
    }
}

Would it make sense to handle it like this? Surely some of the code for drawing is going to be repeated?

So:

abstract class GraphicObject {

    public virtual void draw()
    {
       // all objects will need to be drawn in a similar way, do this here.
    }
}

and then in my circle class do all the unique stuff to the circle

public override void draw() {
    //Do unique circle drawing stuff here
    base.draw();
}

then call the base draw method at the end of the method to finish.

I struggle to see a scenario where I would need to really use an abstract method without repeating code in some form.

Consider the case where the virtual method returns a value. Consider a factory style method which is used for creating values

class Factory { 
  public abstract Node CreateNode(); 
}

An abstract method works well here because it doesn't put any responsibility on Factory to actually produce a Node value. Instead it just declares a Node should be provided. If instead you made it a virtual method then Factory would have to pick a default value. How can it produce a Node if it doesn't know what type of factory it is?

public virtual Node CreateNode() { 
  return ???;
}

Unless you have things that must be done for all shapes at the beginning or ending of the draw call, then you wouldn't put code in the abstract class to do it.

If there are common things to be done that are done at different points during draw, then you can put them in the abstract class in, say, protected methods; only classes that inherit will be able to call them, and that will put that common code into one place.

The use of abstract methods is to ensure that (1) a class using a shape has access to those methods without knowing what subclass it holds a reference to. So, for instance, a page could have a list of shapes, and call draw on each one (because it is defined in the superclass) even though each one is a specific subclass shape. If draw() is not defined in shape, then you cannot call draw on each shape in a list.

(I am more familiar with java and have used java terminology -- I gather you are more familiar with something else, given the format for your inheritance and the use of "base.". Translate as necessary...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM