LearnStanmorephysics

Grade 12 · Matric Mastery

Your first class

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

Hints
  1. The implementation header repeats the class name: constructor TLearner.Create(sName : String; iMark : Integer);
  2. Inside Create just two lines: fName := sName; and fMark := iMark;
  3. 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;

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.