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
- Implement GetAverage (a Real — average of the two marks)
- Implement SetName (mutator) and ToString as: Zanele : 75.5%
- Handler: create from the edits, memo the ToString, then SetName to Z. Zulu and memo ToString again
Hints
- GetAverage: Result := (fMark1 + fMark2) / 2; — dividing with / gives the Real.
- ToString: Result := fName + ' : ' + FloatToStrF(GetAverage, ffFixed, 6, 1) + '%';
- 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;