Understand the Delphi Class (vii)

Source: Internet
Author: User

What is polymorphism? My understanding is that the same method will have different implementations in different objects, that's all.

unit Unit1;
interface
uses
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs, StdCtrls;
type
 TForm1 = class(TForm)
  Button1: TButton;
  Button2: TButton;
  Button3: TButton;
  procedure Button1Click(Sender: TObject);
  procedure Button2Click(Sender: TObject);
  procedure Button3Click(Sender: TObject);
 end;
Three classes are defined, and the second two classes inherit from the first class Tbass TBass = class
  procedure alert; virtual;

{With the virtual designator, this method may be modified (or overwritten)}

{This method is called a virtual method} end;
 TChild1 = class(TBass)
  procedure alert; override; {override 表示修改父类的同名方法}
 end;
 TChild2 = class(TBass)
  procedure alert; override;
 end;
var
 Form1: TForm1;
implementation
{$R *.dfm}
{ TBass }
procedure TBass.alert;
begin
 ShowMessage('is Bass');  {同一个方法, 在不同类里有不同的实现}
end;
{ TChild1 }
procedure TChild1.alert;
begin
 ShowMessage('is TChild1'); {同一个方法, 在不同类里有不同的实现}
end;
{ TChild2 }
procedure TChild2.alert;
begin
 ShowMessage('is TChild2'); {同一个方法, 在不同类里有不同的实现}
end;
Test 1:procedure TForm1.Button1Click(Sender: TObject);
var
 bass: TBass; {定义 TBass 的变量}
begin
 bass := TBass.Create;
 bass.alert; {is Bass}
 bass.Free;
end;
Test 2:procedure TForm1.Button2Click(Sender: TObject);
var
 bass: TBass;      {注意还是定义 TBass 的变量}
begin
 bass := TChild1.Create; {但这里是通过 TChild1 建立对象}
 bass.alert; {is TChild1}
 bass.Free;
end;
Test 3:procedure TForm1.Button3Click(Sender: TObject);
var
 bass: TBass;      {注意还是定义 TBass 的变量}
begin
 bass := TChild2.Create; {但这里是通过 TChild2 建立对象}
 bass.alert; {is TChild2}
 bass.Free;
end;
{Summary: Now the same is the Bass.alert method, through the implementation of different objects, with different functions, this is polymorphism!}

End.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.