Domanda

What is the purpose of defining non-abstract methods in abstract classes and abstract methods in non-abstract classes?

What where the useful scenarios for using these?

È stato utile?

Soluzione

  1. You cannot declare abstract method in non-abstract class. From C# spec:

    10.6.6 Abstract methods

    (...) Abstract method declarations are only permitted in abstract classes (§10.1.1.1).

  2. Non-abstract method in abstract class is a method that do not have to (or sometimes even can't) be reimplemented in derived classes.

    They provide some implementation which is independent and the same across all derived classes (when don't mark as virtual) or which can be overridden, but has some default behavior (with virtual modifier).

    That's mainly how abstract classes differ from interfaces (which cannot contain any implementations).

Altri suggerimenti

One feature of abstract classes is that you can have implemented base class functionality in addition to abstract methods that must be implemented. This can be beneficial for code reuse.

There can not be abstract methods in non abstract classes.

What is the purpose of defining non-abstract methods in abstract classes?

An abstract class declaring nothing but abstract methods is little different than declaring an interface; generally, an abstract class includes some minimum/default implementation-independent functionality while leaving abstract stubs for things that are implementation-dependent.

...and abstract methods in non-abstract classes?

You cannot declare abstract methods in a non-abstract class.

define your method as Virtual instead of Abstract in this case.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top