delphiclassdelphi-units

Are units in delphi same as classes in other languages?


I need to write some Delphi code, but I have no prior experience with Delphi. I've seen people writing some code, known as unit1 or unit2 and import it using the code inside them. So, can I see the unit as a class in Java or C#?


Solution

  • No. A unit is a source code file in Delphi. You can essentially think of it as a namespace whose scope is exactly the same as the current file.

    Within a unit, you can define classes, with type definition syntax. It looks like this:

    type
      TMyClass = class(TParentClass)
      private
        //private members go here
      protected
        //protected members go here
      public
        //public members go here
      end;
    

    Any methods are declared below the type declaration, not inline, which makes the code easier to read because you can see the composition of a class at a glance instead of having to wade through its implementation.

    Furthermore, each unit has two main sections, called interface and implementation. A type declaration can be placed in either section, but implementing code is not valid in interface. This allows for a language concept similar to Java's or C#'s public and private classes: any type declared in interface is visible to other units that use this unit ("public"), while any type declared in implementation is visible only within the same unit.