Abstract Class in Delphi

戏子无情 提交于 2019-12-06 17:48:06

问题


I am using a component suite which has many abstract classes. Now I want to apply polymorphism but I am getting Error Abstract Class when I create my object.

Should I override all methods which are virtual even if I don't need it? Are there any workaround or solution?


回答1:


In order to make an instance of a class, you need to override all methods that are declared as virtual abstract. Even if you don't use them.

If you really want a work around, you can use empty methods. But I won't recommend that.

And to add some more information on the subject:

A method is abstract if it is declared with virtual abstract:

procedure MyMethod(const AMyParameter: Integer); virtual; abstract;

Trivia: You can even override a method as abstract:

procedure MyMethod(const AMyParameter: Integer); override; abstract;

You need to override these methods in order to instantiate from that class.

And you can declare an entire class as abstract:

type
  TMyClass = class abstract (TMyAncestor)
  end;

You get a warning if you try to instantiate that class.

The counterpart is a sealed class:

type
  TMyClass = class sealed (TMyAncestor)
  end;

You get a warning if you try to inherit from that class.

You can also seal methods, but you need the keyword final for that.

procedure MyMethod(const AMyParameter: Integer); override; final;



回答2:


Delphi doesn't have abstract classes as such, only abstract methods. You will get an abstract method exception raised if you call an abstract method.

Put simply you must not call abstract methods. The compiler emits a warming if it detects you instantiating a class with abstract methods. Good practise is to ask the compiler to turn these warnings into errors.




回答3:


Your descendant class is still abstract if

  1. it's declared abstract, or
  2. it has at least one method declared abstract, or
  3. it doesn't override and implement all abstract methods from its ancestors



回答4:


It will produce an error if you override the abstract constructor as it automatically puts inherited into the new constructor which of course is calling the abstract constructor if you use the code auto complete.

e.g.

type
  TMyclass = class (TObject)
  public
    constructor Create(AOwner : TComponent); dynamic; abstract;
  end;

  TMyclass2 = class(TMyclass)
  public
    Constructor Create(AOwner : TComponent); override;
  end;

implementation

constructor TMyclass2.Create(AOwner: TComponent);
begin
  inherited;

end;


来源:https://stackoverflow.com/questions/6187018/abstract-class-in-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!