简体   繁体   中英

Difference in deriving from abstract and non abstract class

In OOP, I see a lot of classes which derive from parent classes, but the parent classes are not marked as abstract. When the class IS marked as abstract, what advantage does this provide?

Thanks

The difference is really pretty pragmatic: an abstract base class is one that is never intended to be instantiated, and so needn't necessarily provide complete implementations. This means the ABC can define a contract for derived classes without implementing the class.

This is convenient in two ways:

  • you can define abstract objects that don't have the full implementation but make assertions about the whole class. One example of this is to have a DrawItem class with a draw() method that's the base class for Circle, Rectangle, and so on. DrawItem can't know how to draw itself, because it doesn't know what it is .

  • you can define classes for which you can have two concrete implementations. This shows up in the Proxy pattern, and can also be used to build, for example, mock objects for testing.

It's more common these days for new languages to define interfaces or modules or mixins for these things; it turns out that using ABCs almost always fall into the use cases for those more intuitive concepts.

Paul Haahr has interesting suggestions , such as:

Don't subclass concrete classes

(read the original, I don't want to copy and paste everything;-).

Paul's writing about Java, but I found at least this part of his advice is applicable to most any OO design task (though pragmatically I still occasionally deviate from it in coding , it's alive and well in my design ;-), even when I'm going to implement it in C++, Python, or whatever. If, after reading Paul's reasoning, you find yourself agreeing with him, you're going to be using a lot more abstract classes in the future (to allow subclassing;-).

To call a class "abstract" is essentially to communicate to your fellow programmers that it's incomplete: they're expected to write a bit more code to be able to make use of it.

There's actually a parallel with partial application of functions in functional programming here...

An abstract class cannot be instantiated by itself; it must be derived from to be instantiated. Essentially, the abstract definition on a class indicates that it was not intended to be instantiated as itself, and the only way to get an instance of it is to inherit from that class, and instantiate the inherited class.

编译器不允许你实例化它的事实?

to give an example of what I think is pertinent:

public abstract class CustomSocket()
{
    CustomSocket()
    {
    }

    public abstract void PleaseOverideMe(CustomSocketConnection c)
    {

    }

}

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