Although there are many classes in the object hierarchy, you are likely to need to create additional classes if you are writing object-oriented programs. The classes you write must descend from TObject or one of its descendants.
The advantage of using classes comes from being able to create new classes as descendants of existing ones. Each descendant class inherits the fields and methods of its parent and ancestor classes. You can also declare methods in the new class that override inherited ones, introducing new, more specialized behavior.
The general syntax of a descendant class is as follows:
Type TClassName = Class (TParentClass) public {public fields} {public methods} protected {protected fields} {protected methods} private {private fields} {private methods} end;
If no parent class name is specified, the class inherits directly from TObject. TObject defines only a handful of methods, including a basic constructor and destructor.
TMyClass = class; {This implicitly descends from TObject} public . . . private . . . published {If descended from TPersistent or below} . . .
If you want the class to descend from a specific class, you need to indicate that class in the definition:
TMyClass = class(TParentClass); {This descends from TParentClass}
For example:
type TMyButton = class(TButton) property Size: Integer; procedure DoSomething; end;
type TMyButton = class(TButton) property Size: Integer read FSize write SetSize; procedure DoSomething; private FSize: Integer; procedure SetSize(const Value: Integer);
The following code is also added to the implementation section of the unit.
{ TMyButton } procedure TMyButton.DoSomething; begin end; procedure TMyButton.SetSize(const Value: Integer); begin FSize := Value; end;
{ TMyButton } procedure TMyButton.DoSomething; begin Beep; end; procedure TMyButton.SetSize(const Value: Integer); begin if fsize < > value then begin FSize := Value; DoSomething; end; end;
Note that the button also beeps when you call SetSize to change the size of the button.
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|