An Object type in Pascal is a structured data type used in object-oriented programming.
Object types are similar to record types, with additional method fields and keywords that specify the scope of the fields.
The structure of an object is illustrated below:
Objects in Pascal contain the following:
Member Variables: These refer to variables defined inside the object.
Member Functions: These refer to methods defined inside the object.
Visibility Keywords: These specify the scope of the fields and methods as either public
, private
, or protected
.
Constructor: A special method that is automatically invoked when an object is created.
Destructor: A special method automatically invoked when an object is destroyed or goes out of scope.
Objects are declared through the type
declaration, as shown below:
type object_name = object
private
field1 : data_type;
field2: data_Type;
//... as many fields as needed
public:
procedure method1;
function method2(): data_type;
//... as many methods as needed
end;
As shown above, all member variables and methods are encapsulated by the type
declaration.
The code below shows how an object can be declared in Pascal:
program exampleObj;// Declaring a person Objecttype Person = object// fields to hold data about a personprivateperson_name : string;age : integer;// methods to view and update person datapublicprocedure setName(n : string);function getName() : string;procedure setAge(a : integer);function getAge() : integer;end;// Defining the object methodsprocedure Person.setName(n : string);beginperson_name := n;end;function Person.getName() : string;begingetName := person_name;end;procedure Person.setAge(a : integer);beginage := a;end;function Person.getAge() : integer;begingetAge := age;end;// creating object instancevarnewPerson : Person;begin//setting object fieldsnewPerson.setName('Alice');newPerson.setAge(20);//output object fieldswriteln('The person''s name is ', newPerson.getName());writeln('The person''s age is ', newPerson.getAge());end.
The above code declares a Person
object using the type
identifier. The object has fields for the person’s name and age. These fields can only be accessed within the module that contains the object due to the private
keyword.
The declaration also includes procedures to change the person’s name and age and functions to retrieve the values of these fields. Each of these procedures and functions is defined after the object’s declaration.
Finally, the code creates an instance of the Person
object and invokes the setName
and setAge
methods to update the person’s name and age. The updated name and age are retrieved using the getName
and getAge
methods and output accordingly.
Free Resources