简体   繁体   中英

Derive abstract class from non-abstract class

Is it OK to derive an abstract class from a non-abstract class or is there something wrong with this approach?

Here´sa little example:

public class Task {
  // Some Members
}

public abstract class PeriodicalTask : Task {
  // Represents a base class for task that has to be done periodicaly.
  // Some additional Members
}

public class DailyTask : PeriodicalTask {
  // Represents a Task that has to be done daily.
  // Some additional Members
}

public class WeeklyTask : PeriodicalTask {
  // Represents a Task that has to be done weekly.
  // Some additional Members
}

In the example above I do not want to make the class Task abstract, because I want to instantiate it directly. PeriodicalTask should inherit the functionality from Task and add some additional members but I do not want to instantiate it directly. Only derived class of PeriodicalTask should be instantiated.

I don't see anything wrong with this approach.

You might have some basic type that can be described in concrete terms. Now, just because an object of this type might be further classified according to some subtype, it does not follow that all such subtypes are just as concrete; they may in turn require further concretization, as it were.

Real-world example:

Person -- concrete (non-abstract)
Sibling: Person -- abstract
Brother: Sibling -- concrete
Sister: Sibling -- concrete

Nothing wrong with it.

If you look at a big hierarchy like WinForms, you will find several layers of abstract types.

MSBuild tasks are also a good (and more relevant) example.

This sort of thing happens all the time: All abstract classes inherit from System.Object , a class that is not abstract by itself.

new System.Object() is sometimes useful for locking, if you don't have anything else around, you could lock over.

Using abstract is not the right approach here then, use a protected or internal constructor, for example. That would prevent instances of PeriodicalTask to be created directly, but its derived classes would still have access to it.

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