1.类成员的可见性

private          //不可见  
protected     //派生类可见  
public           //可见  
published     //可见。用于运行时信息  
automated   //可见。用于兼容






2.类方法调用


inherited(继承):就是调用父类的函数。如果不带参数就是默认调用父类的同名函数;如果带参数则表明子类中的函数的参数个数可能比祖先类要多取其中的几个参数传过去


例如



祖先类有个函数 Create(AName:string);  
子类有个函数 Create(AName:string;AComponent:TObject);override;  
那么子类的Create函数内就可以这样调用祖先类:  
procedure TAClass.Create(AName:string;AComponent:TObject);  
begin  
Inherited Create(AName);  
end;



类方法可以看做是公共方法,对于类方法的调用。例如:

constructor TMyClass.Create;  
begin  
  inherited;  
  MyProc;  //调用类方法  
end;  
  
class procedure  TMyClass.MyProc;  
begin  
  ShowMessage('OK'); //类方法实现  
end;  
procedure TForm1.FormCreate(Sender: TObject);  
var  
  myclass : TMyClass;  
begin  
  TMyClass.MyProc;  //用类名调用类方法  
  myclass := TMyClass.Create;   //初始化对象  
  myclass.MyProc;  //对象调用类方法  
  myclass.Free; //释放对象  
end;






3.覆盖虚方法


//定义父类、子类方法  
{父类}  
TParent = class  
protected  
  function MyFun(i:Integer):Integer;dynamic; //动态方法  
  procedure MyProc; virtual;  //虚方法  
end;  
{子类}  
TChild = class(TParent) //继承父类  
protected  
  function MyFun(i:Integer):Integer;override;  //覆盖方法  
  procedure MyProc; override;  
end;




实现类的方法、过程


{TParent}  
function TParent.MyFun(i:Integer): Integer;  
begin  
  Inc(i);  //i++  
  Result:=i;  //返回变量i  
end;  
procedure TParent.MyProc;  
begin  
  ShowMessage('Parent');  
end;  
  
{TChild}  
function TChild.MyFun(i:Integer):Integer;  
begin  
  i:= inherited MyFun(i);  //继承父类的MyFun方法  
  Inc(i);  
  Result:=i;  
end;  
procedure TChild.MyProc;  
begin  
  inherited; //调用父类的MyProc方法  
  ShowMessage('child');  
end;




我们可以注意到在实现子类方法的时候利用inherited来继承父类的方法。


 


4.抽象类考虑到抽象类在某种程度上可以用接口来代替,所以这里我并不在仔细对抽象类进行介绍。直接给例子:


{父类}  
TParent = class  
protected  
  function MyFun(i:Integer):Integer;abstract; //动态方法  
end;  
{子类}  
TChild = class(TParent) //继承父类  
protected  
  function MyFun(i:Integer):Integer;override;  //覆盖方法  
end;




对类方法的实现也和第3点类方法的覆盖相类似。


5.方法重载



{1.关于方法重载: 
 2.过程和函数之间可以重载 
 3.类内重载必须有 overload 关键字 
 4.子类重载必须有 overload 关键字,夫类可以没有 
 5.如果夫类是虚函数(virtual dynamic),子类重载时需要加 reintroduce 修饰词 
 6.published 区内不能重载}  
 //方法重载  
 TMyClass2 = class  
 protected  
   procedure MyProc1(i:Integer); overload; //重载方法  
   function MyFun1(s1,s2:string): string; overload;  
 end;




对类方法的实现也和第3点类方法的覆盖相类似。


 


6.参数默认值


例如


//带默认值的参数只能在后面  
function MyFun(a:Integer; b:Integer=1; c:Integer=2): Integer;  
begin  
  Result := a + b + c;  
end;




如在调用该函数时,对参数已赋值。则默认值不起作用;如未赋值,则用默认值进行操作。


7.属性的自动完成


在Type区写入


TMyClass = class  
    property s: string;  
  end;  
然后把光标放在其中,执行Ctrl+Shift+C。Delphi会自动生成属性的相关代码


TMyClass = class  
  private  
    Fs: string;  
    procedure Sets(const Value: string);  
  published  
    property s: string read Fs write Sets;  
  end;  
{ TMyClass }  
procedure TMyClass.Sets(const Value: string);  
begin  
  Fs := Value;  
end;