delphi实现一个类继承抽象类并实现接口

来源:互联网 发布:广州手趣网络 招聘 编辑:程序博客网 时间:2024/06/05 14:16

 问题描述:TSaleOutDao即要继承抽象类TABizDao又要实现接口TIBizDao.

解决办法:先用抽象类继承TIBizDao,然后再把需要实现的接口方法声明为抽象方法。然后再用

TSaleOutDao继承TABizDao.

  1. //IBizDao.pas单元文件
  2. unit IBizDao;
  3. interface
  4. type
  5.   TIBizDao=interface
  6.     function aaa:string;
  7.   end;
  8. implementation
  9. end.

 

  1. //ABizDao.pas单元文件
  2. unit ABizDao;
  3. interface
  4. uses 
  5.   IBizDao;//引用父类单元
  6. type
  7.   {特别注意,同一个单元内的两个类会被任务是友元类,即如果把SaleOutDao也写在该单元中,
  8. SaleOutDao可以直接访问ABizDao中的私有变量TableName并赋值}
  9.   TABizDao=class(TInterfacedObject,TIBizDao)
  10.   private
  11.     TableName:string;
  12.   protected
  13.     
  14.   public
  15.     constructor create;
  16.     destructor destroy;override;
  17.     procedure SetTableName;virtual;abstract;
  18.     procedure SetTableNameEx(FName:string);
  19.     function GetTableNameEx:string;
  20. {//虽然是继承自接口,但不实现接口的方法;aaa声明为抽象方法,在子类实现}
  21.     function aaa: String;virtual;abstract;
  22.   end;
  23. implementation
  24. { ABizDao }
  25. constructor TABizDao.create;
  26. begin
  27.   Self.SetTableName;
  28. end;
  29. destructor TABizDao.destroy;
  30. begin
  31.   inherited;
  32. end;
  33. function TABizDao.GetTableNameEx: string;
  34. begin
  35.   Result:=TableName;
  36. end;
  37. procedure TABizDao.SetTableNameEx(FName: string);
  38. begin
  39.   Self.TableName:=FName;
  40. end;
  41. end.

 

  1. //SaleOutDao.pas单元文件
  2. unit SaleOutDao;
  3. interface
  4. uses
  5.   ABizDao,IBizDao;//引用父类单元
  6. type
  7.   TSaleOutDao=class(TABizDao)
  8.   private
  9.   protected
  10.     
  11.   public
  12.     constructor create;
  13.     destructor destroy;override;
  14.     procedure SetTableName;override;
  15.     function aaa: String;override;
  16.   end;
  17. implementation
  18. {实现接口的方法}
  19. function TSaleOutDao.aaa: String;
  20. begin
  21.   Result:='aaa';
  22. end;
  23. constructor TSaleOutDao.create;
  24. begin
  25.   inherited;{加上关键字inherited会调用父类构造函数,如果不加的话不会执行TABizDao.create}
  26. end;
  27. destructor TSaleOutDao.destroy;
  28. begin
  29.   inherited;
  30. end;
  31. {实现抽象类的抽象方法}
  32. procedure TSaleOutDao.SetTableName;
  33. begin
  34.   inherited;
  35.   SetTableNameEx('UserInfo');
  36. end;
  37. end.
原创粉丝点击