LearnStanmorephysics

Grade 12 · Matric Mastery

Getters, setters & toString

Grade 12 · Object-oriented programming · Lesson and coding task · about 16 minutes

Open this task in the Delphi workspace →

The exam's favourite trio of methods:

Accessor (getter) — a function returning a field (or something computed from fields):

function TLearner.GetAverage : Real;
begin
  Result := (fMark1 + fMark2) / 2;
end;

Mutator (setter) — a procedure that changes a field:

procedure TLearner.SetName(sName : String);
begin
  fName := sName;
end;

toString — one String that sums the object up. Convention: build it from the other methods where you can:

function TLearner.ToString : String;
begin
  Result := fName + ' : ' + FloatToStrF(GetAverage, ffFixed, 6, 1) + '%';
end;

Notice ToString calling GetAverage — methods of the same object call each other directly by name.

Your task

A learner has two test marks. Implement GetAverage, SetName and ToString; then create the object, show it, rename it with the setter, and show it again.

What you will do

Hints
  1. GetAverage: Result := (fMark1 + fMark2) / 2; — dividing with / gives the Real.
  2. ToString: Result := fName + ' : ' + FloatToStrF(GetAverage, ffFixed, 6, 1) + '%';
  3. In the handler the object is created once; SetName('Z. Zulu') changes it; ToString shows the change.
Model solution
type
  TLearner = class
  private
    fName : String;
    fMark1, fMark2 : Integer;
  public
    constructor Create(sName : String; iM1, iM2 : Integer);
    function GetAverage : Real;
    procedure SetName(sName : String);
    function ToString : String;
  end;

constructor TLearner.Create(sName : String; iM1, iM2 : Integer);
begin
  fName := sName;
  fMark1 := iM1;
  fMark2 := iM2;
end;

function TLearner.GetAverage : Real;
begin
  Result := (fMark1 + fMark2) / 2;
end;

procedure TLearner.SetName(sName : String);
begin
  fName := sName;
end;

function TLearner.ToString : String;
begin
  Result := fName + ' : ' + FloatToStrF(GetAverage, ffFixed, 6, 1) + '%';
end;

procedure TfrmAcc.btnGoClick(Sender: TObject);
var
  objL : TLearner;
begin
  objL := TLearner.Create(edtName.Text, StrToInt(edtM1.Text), StrToInt(edtM2.Text));
  memOutput.Lines.Add(objL.ToString);
  objL.SetName('Z. Zulu');
  memOutput.Lines.Add(objL.ToString);
end;

About this material

This platform provides original CAPS-aligned practice material and study tools. Content is machine-verified and has not been reviewed by subject specialists. It is not affiliated with or endorsed by the Department of Basic Education. Learners should also use official past papers and consult their teachers where uncertain.