Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Hacking a final method in Delphi 8

Title: Hacking a final method in Delphi 8 Question: Delphi 8 provides the facility to declare a method of a class as final, but if you really want to override it? Answer: In Delphi8 the final keyword is introduced, it can be used to specify that a method in a class cannot be reintroduced, in other words, it can be used to break a polymorphic chain of methods. Why would you want to do that?, one reason is to allow the JITer to optimise method calls, other can be that you dont want anybody else to extend the functionallity of your code. Nevertheless, using a dirty hack you can continue to override a final method, supose you have the following code: type TBaseClass = class public procedure DoSomething;virtual; end; TDerivedClass = class(TBaseClass) public procedure DoSomething;override;final; end; Now, since DoSomething is final, if you declare TAnotherClass = class(TDerivedClass) public procedure DoSomething;override; end; the compiler gives you the following error: [Error] Project1.dpr(21): Cannot override a final method If you modify the code for TAnotherClass as follows: TAnotherClass = class(TDerivedClass) public procedure DoSomething;reintroduce;virtual; end; You can still call the inherited method like this: procedure TAnotherClass.DoSomething; begin inherited; // your code here end; Enjoy.