Grade 12 · Object-oriented programming · Lesson and coding task · about 16 minutes
Open this task in the Delphi workspace →
Declaring a class is only half the work — each method still needs its implementation, written below the class with the class name in front:
constructor TLearner.Create(sName : String; iMark : Integer);
begin
fName := sName; // copy the parameters into the fields
fMark := iMark;
end;
function TLearner.ShowInfo : String;
begin
Result := fName + ' scored ' + IntToStr(fMark) + '%';
end;
Inside a method you reach the fields directly by name — fName means "this object's fName". Then the form's button click brings it to life:
objL := TLearner.Create(edtName.Text, StrToInt(edtMark.Text));
memOutput.Lines.Add(objL.ShowInfo);
Try reading objL.fName from the handler — encapsulation will slam the door in your face (a very educational door).
What you will do
- Implement the constructor: copy both parameters into the fields
- Implement ShowInfo so it returns: Karabo scored 80%
- In the click handler: create the object from the edit boxes and memo its ShowInfo
Hints
- The implementation header repeats the class name: constructor TLearner.Create(sName : String; iMark : Integer);
- Inside Create just two lines: fName := sName; and fMark := iMark;
- ShowInfo builds its Result from fName and IntToStr(fMark).
Model solution
type
TLearner = class
private
fName : String;
fMark : Integer;
public
constructor Create(sName : String; iMark : Integer);
function ShowInfo : String;
end;
constructor TLearner.Create(sName : String; iMark : Integer);
begin
fName := sName;
fMark := iMark;
end;
function TLearner.ShowInfo : String;
begin
Result := fName + ' scored ' + IntToStr(fMark) + '%';
end;
procedure TfrmApp.btnCreateClick(Sender: TObject);
var
objL : TLearner;
begin
objL := TLearner.Create(edtName.Text, StrToInt(edtMark.Text));
memOutput.Lines.Add(objL.ShowInfo);
end;