简体   繁体   中英

How to access base (super) class in Delphi?

In C# i can access base class by base keyword, and in java i can access it by super keyword. How to do that in delphi? suppose I have following code:

  type
    TForm3 = class(TForm)
  private
    procedure _setCaption(Value:String);
  public
    property Caption:string write _setCaption; //adding override here gives error
  end;

  implementation


procedure TForm3._setCaption(Value: String);
begin
  Self.Caption := Value; //it gives stack overflow      
end;

You are getting a stackoveflow exception because the line

Self.Caption := Value;

is recursive.

You can access the parent property Caption casting the Self property to the base class like so :

procedure TForm3._setCaption(const Value: string);
begin
   TForm(Self).Caption := Value;
end;

or using the inherited keyword

procedure TForm3._setCaption(const Value: string);
begin
   inherited Caption := Value;
end;

You should use inherited keyword:

procedure TForm3._setCaption(Value: String); 
begin 
  inherited Caption := Value;
end;

base (C#) = super (java) = inherited (Object Pascal) (*)

The 3 keywords works in the same way.

1) Call base class constructor
2) Call base class methods
3) Assign values to base class properties (assume they are not private, only protected and public are allowed)
4) Call base class destructor (Object Pascal only. C# and Java doesn't have destructors)


(*) Object Pascal is preferable instead of Delphi or Free Pascal because Object Pascal is the name of a program language while Delphi and Free Pascal are compilers of Object Pascal.

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