How do I invoke a descendant's implementation when I call a method on a base class?

前端 未结 1 868
臣服心动
臣服心动 2021-01-21 06:19

My top level class is TBaseDB, which has a descendant TCommonDB (, and TCommonDB will have multiple descendants, like TProdDB

相关标签:
1条回答
  • 2021-01-21 07:02
    program Project1;
    
    {$APPTYPE CONSOLE}
    
    uses
      SysUtils;
    
    type
      TFruit = class
      public
        procedure ShowMessage; virtual; abstract;
      end;
    
      TApple = class(TFruit)
      public
        procedure ShowMessage; override;
      end;
    
      TOrange = class(TFruit)
      public
        procedure ShowMessage; override;
      end;
    
    
    { TApple }
    
    procedure TApple.ShowMessage;
    begin
      Writeln('I''m an apple!');
    end;
    
    { TOrange }
    
    procedure TOrange.ShowMessage;
    begin
      Writeln('I''m an orange!');
    end;
    
    var
      fruit: TFruit;
    
    begin
    
      fruit := TApple.Create;
    
      fruit.ShowMessage;
    
      Writeln('Press Enter to continue.');
      Readln;
    
    end.
    

    The keyword abstract allows you to have no implementation at all in the base class. You can also, however, have an implementation there as well:

    program Project2;
    
    {$APPTYPE CONSOLE}
    
    uses
      SysUtils;
    
    type
      TFruit = class
      public
        procedure ShowMessage; virtual;
      end;
    
      TApple = class(TFruit)
      public
        procedure ShowMessage; override;
      end;
    
      TOrange = class(TFruit)
      public
        procedure ShowMessage; override;
      end;
    
    
    { TFruit }
    
    procedure TFruit.ShowMessage;
    begin
      Writeln('I''m a fruit.');
    end;
    
    { TApple }
    
    procedure TApple.ShowMessage;
    begin
      inherited;
      Writeln('I''m an apple!');
    end;
    
    { TOrange }
    
    procedure TOrange.ShowMessage;
    begin
      inherited;
      Writeln('I''m an orange!');
    end;
    
    var
      fruit: TFruit;
    
    begin
    
      fruit := TApple.Create;
    
      fruit.ShowMessage;
    
      Writeln('Press Enter to continue.');
      Readln;
    
    end.
    

    Exercises:

    1. In each case, what happens if you create an instance of TFruit?
    2. In the second case, what does inherited in TApple.ShowMessage and TOrange.ShowMessage mean? Do they need to be at the top of the procedures? What happens if you omit them?
    0 讨论(0)
提交回复
热议问题