Object methods in Pascal are methods defined inside an object that can access the object’s data fields. An object method can be invoked by using the dot operator ( .
) on an object instance.
The process is illustrated below:
The code below shows how object methods can be invoked in Pascal:
program invokeMethods;// Declaring a person Objecttype Person = object// fields to hold data about a personprivateperson_name : string;age : integer;// object methodspublic// constructor for object instantiationconstructor init(n : string; a : integer);// procedures to update data fieldsprocedure setName(n : string);procedure setAge(a : integer);// functions to return data field valuesfunction getName() : string;function getAge() : integer;end;// Defining the object methodsconstructor Person.init(n : string; a : integer);beginperson_name := n;age := a;end;procedure 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// initializing objectnewPerson.init('Alice', 30);//output object fieldswriteln('The person''s name is ', newPerson.getName());writeln('The person''s age is ', newPerson.getAge());//setting object fieldsnewPerson.setName('Bob');newPerson.setAge(20);//output object fieldswriteln('The person''s name is ', newPerson.getName());writeln('The person''s age is ', newPerson.getAge());end.
The Person
object holds data about a person’s name and age.
The code defines a constructor
that can be invoked to initialize the object with specific values. setName
and setAge
can update a person’s name and age, respectively. Similarly, the getName
and getAge
methods return the person’s name and age, respectively. Since all these methods are classified under the public
keyword, they are always accessible.
Once the object newPerson
is created, the constructor
is invoked through the dot operator ( .
) to initialize the values for the name and age to “Alice” and , respectively. The getName
and getAge
methods are also invoked through the dot operator to return the field values, which are output accordingly. Since the object declaration does not list any parameters for the getName
and getAge
functions, no arguments are provided when the method is invoked.
The setName
and setAge
methods are then invoked to change the values for name and age to “Bob” and , respectively. The updated values are retrieved and output.
Free Resources