Can I store data in an abstract base class?

I have an abstract class:

type TInterfaceMethod = class abstract public destructor Destroy; virtual; abstract; function GetBasePlan: Word; virtual; abstract; procedure CountBasePlan; virtual; abstract; procedure Calculate; virtual; abstract; procedure PrepareForWork; virtual; abstract; end; 

and derived class:

 type TFogelMethod = class(TInterfaceMethod) private matrix: TFogelMatrix; BasePlan: Word; public constructor Create(var matr: TFogelMatrix); procedure Calculate; function GetBasePlan: Word; procedure CountBasePlan; procedure PrepareForWork; destructor Destroy; end; 

The question is, can I put the GetBasePlan and CountBasePlan methods in the base class, make them only virtual - and not abstract, as it is now - and also place the base plan there? So, can I do this:

 type TInterfaceMethod = class abstract private BasePlan: Word; public destructor Destroy; virtual; abstract; function GetBasePlan: Word; virtual; procedure CountBasePlan; virtual; procedure Calculate; virtual; abstract; procedure PrepareForWork; virtual; abstract; end; 

In case I can do this, will it be good from the point of view of object-oriented design and how can I accurately access this member from derived classes?

+3
source share
2 answers

Yes, you can. Abstract classes are classes, and they can have implementations.

By adding the abstract keyword to a class, you deny an instance of the class. It does not require abstract methods.

You can create an instance of a class with abstraction methods, but this will lead to a warning at compile time and an exception if the method is called.

Interfaces have no implementation, they must be implemented by classes (which can be abstract, by the way).

+8
source

Just to add to the answer of Gamecat, you can not only, but also post your common code there.

+7
source

All Articles