IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
Delphi
Search Delphi Group:

Advanced
-Collapse +Expand Delphi To/From
To/FromCODEGuides
-Collapse +Expand Delphi Store
PRESTWOODSTORE

Prestwood eMagazine

October Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgrammingDelphi for W...OOP   Print This     
  From the February 2016 Issue of Prestwood eMag
 
Delphi OOP:
A 10 Minute Your First Delphi Class Quick Start
 
Posted 16 years ago on 2/26/2008
Take Away:

Beginners example of creating and using a class. Early versions of Delphi use the standard OO private, protected, and public visibility specifiers plus add published for RTTI info. Later versions of Delphi add strict private and strict protected for a true OO implementation.

KB100889

Got 10 minutes? Want to get started with Your First Delphi Class?

This article is part of our series of 10 Minute Quick Starts. Each quick start is step by step, assumes you know very little about the subject, and takes about 10 minutes. You can use them to scratch the service of areas you want to learn and as a quick review when returning to something after a long absence.

Your First Delphi Class

Object Orientation (OO) is about software design, divide and conquer, and most of all code re-use. Prior to object orientation, code reuse was about libraries of code. For example Pascal units and C header files. Libraries are a common repository where code can be stored that will or might be used at a later time by any number of application projects. Typical applications that are not object oriented end up with a library of code that is not very well organized (if at all) and sometimes referred to as spaghetti code. For example, during the coding of your application, when you find a function or procedure that you will call from two locations, you put the routine in a unit and add that unit to each units uses' clause. Perhaps youll name the unit the same name as the application or simply utils.pas or misc.pas.

By the time youre done coding your application, you might have several libraries of reusable code. Coding on the fly like this is useful, but if you knew prior to coding what routines would be reusable, you could organize your code better. Object orientation allows you to do this and much more.

Defining the class

The proper way to begin is to generically analyze what it is you want to accomplish. From there you can begin to define objects, relationships and properties that respond to the problem domain.

Pieces of a class

The class declaration consists of a header and four (4) declaration sections. The header contains the name of the class and what class, if any, this class inherits from. For example, our class will be called TSysTime and will inherit from TObject, so our header would look like the following:

TSysTime = class(TObject)
 

The four traditional Delphi visibility specifiers are private, protected, public, and published.

  • Private - The properties and methods defined in this section can only be seen by this class.
  • Protected - The properties and methods defined in this section can be seen by this class and any class that descends from it.
  • Public - The properties and methods defined in this section can be seen by any user of the class.
  • Published - The properties and methods defined in this section can be seen by any user of the class. Add additional keyword property. Published is used primarily for component creation.

Note: I used the term "tranditional Delphi visibility specifiers" above to mean the specifiers available since Delphi 1.0. More on this at the end of this tutorial.

A class has two methods which are called a constructor and a destructor. These two methods are called automatically when an object is created and destroyed. Assigning an object variable the address of the create method of a class automatically calls the constructor (i.e. MyObject := TMyObject.Create ).

Calling an objects Free method will automatically call the destructor (i.e. MyObject.Free ). The constructor and destructor are always public, no matter where they are declared in the class declaration.

Two rules of thumb to remember:
  1. If you inherit a method from a class, and the ancestor method is virtual, override the method.
  2. If anyone may override a method declared in your class, declare it virtual.

Part 1: Simple Class Example

In Part 1, we will create a class in one unit and use it from a form. Although you can add your classes to the form's unit, it's more standard and reusable to put your classes in their own units. You can group your classes in units as you see fit. Grouping them by descendant tree or common usage is a common approach.

And here, we, go...

  1. Create a new project in a folder named FirstClass and name the project FirstClass too. When you save the form, save the form's unit as "FirstClassUnit". and place a single button on it. We'll use this button later to exercise our new class. If you need help with this, refer to our  A 10 Minute Delphi for Win32 Quick Start.

     
  2. Create Person class unit. Click File | New | Unit then File | Save As. Name the unit Person.pas.

     
  3. Add our Person class to the unit (see highlighed below) and save. In this class we have two private members, a constructor, and two properties. Properties are special Delphi class methods that allow you to use dot notation to refer to the values. Optionally, these properties can use accessor methods (also known as getters and setters). In this case, our properties read and write directly to the private member fields so you do not need to implement them using functions and procedures in the implementation section.
     
    unit Person;
     
    interface
     
    type  //Custom types including classes.
      TPerson = class(TObject)  //Start of class.
      private
        FName: String;
        FAge: Integer;
      public
        constructor Create; virtual;
        property Name: String read FName write FName;
        property Age: Integer read FAge write FAge;
      end;  //End of class.
     
    implementation
     
    constructor TPerson.Create;
    begin
      inherited;  //Call the parent Create method
     
      //Set defaults.
      FName := 'unknown';
      FAge := 0;
    end;  //End of constructor method.

    end.  //End of unit.
     
  4. Use Class from form.
     
    4a. Add unit to uses. Before you can use your class, you have to let the compiler know it exists by adding the unit file to the uses as follows:
     
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls, Person;
     
    4b. Create object and use in button. Declare a variable of type TPerson (our instance object), then create the object from the class and use it. Double click the button on our form and alter as follows:
     
    procedure TForm2.Button1Click(Sender: TObject);
    var
      Lisa: TPerson;  //Declare object variable.
    begin
      Lisa := TPerson.Create;  //Create object from class.
      
     
    //Use it. Show defaults.
      ShowMessage(Lisa.Name + ' is ' + IntToStr(Lisa.Age));
      
      //Use it. Set member fields then show.
      Lisa.Name := 'Lisa';
      Lisa.Age := 34;
      ShowMessage(Lisa.Name + ' is ' + IntToStr(Lisa.Age));
    end;
     
  5. Test. Click Project | Compile FirstClass to test your syntax. If you have errors fix them. Then click Run | Run and click our form button.
     
    The first time you click our button, the class default values that we set in our constructor are used.

     
    The second time, you see the values we set. The current values of an object instances member fields and properties is also know as the current state of the instance object. Sometimes loosely referred to as the current state of the class.

Part 2: Class Inheritance

The concept of a class makes it possible to define subclasses that share some or all of the parent class characteristics. This is called inheritance. Inheritance also allows you to reuse code more efficiently. With inheritance, you are defining an "is-a" relationship (i.e. a chow is-a dog).

Note: It's interesting to contrast an "is-a" inheritance relationhip with a "behaves-as" or a "looks-like" interface relationship. Essentially you design your classes top to bottom using inheritance. Ignoring inheritance, if there are various classes that need to behave the same, or look the same, that's when you'll use interfaces. Search this knowledge base for Interfaces for more information. 

In part 2 we will create a TMom class that is-a TPerson with one additional property...

Time To Sign In

You must sign in to read the rest of this document.

Not a member? Join now! Membership is instant and free!

UserID or Email:  Enter your account email, permanent UserID, or current display name.
Password: 
    Remember Me

Or...
 Sign Up  Forgot Password?

More Info

Article:  A 10 Minute Delphi for Win32 Quick Start
Code:  Delphi Inheritance (=class(ParentClass))

Comments

1 Comments.
Share a thought or comment...
Comment 1 of 1

Prestwood solution is a technology hub that is working in solving the issues related to the technology. And essaypro reviews helps to solve writing-related issues, and to have the provision of the best technology to the users through this software house in the form of useful software.

Posted 51 months ago
 
Write a Comment...
...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.


Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P157A1
Enter key:
Article Contributed By Mike Prestwood:

Mike Prestwood is a drummer, an author, and creator of the PrestwoodBoards online community. He is the President & CEO of Prestwood IT Solutions. Prestwood IT provides Coding, Website, and Computer Tech services. Mike has authored 6 computer books and over 1,200 articles. As a drummer, he maintains play-drums.com and has authored 3 drum books. If you have a project you wish to discuss with Mike, you can send him a private message through his PrestwoodBoards home page or call him 9AM to 4PM PST at 916-726-5675 x205.

Visit Profile


Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Beginner

1 Beginner Level Question

Question #1: Multiple Choice

Given this class:

TPerson = class(TObject)
end; 

Which of the following is the correct syntax for creating an object instance from a class?

Answer:
1. 

Declare a variable:

var
  Lisa: TPerson;

Create instance:

Lisa := TPerson.Create; 
2. 

Declare a variable:

var
  Lisa: TPerson;

Create instance:

TPerson Lisa := TPerson.Create; 
3. 

Declare a variable:

var
  Lisa: TPerson;

Create instance:

Lisa := Person.Create; 
4. 

Declare a variable:

var
  Lisa: TPerson;

Create instance:

Lisa := New TPerson; 
5. 

Declare a variable:

var
  Lisa TPerson;

Create instance:

Lisa = TPerson.Create; 

 KB Article #100889 Counter
23573
Since 4/2/2008
Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site: 
www.prestwood.com


©1995-2024 Prestwood IT Solutions.   [Security & Privacy]