This code is written in Free Pascal and cross compiled for the QL:
Code: Select all
{
Program to demonstrate classes on the QL.
This example blatently copied from:
https://www.tutorialspoint.com/pascal/pascal_classes.htm
A few minor amendments and extra comments by Norm.
}
{$mode objfpc} // directive to be used for defining classes
{$m+} // directive to be used for using constructor
{
Define the class...
}
type
Rectangle = class
const
minWidth = 2;
minHeight = 2;
private
height, width: integer;
procedure drawTopBottom;
procedure drawMiddle;
public
constructor create(h, w: integer);
procedure setheight(h: integer);
function getheight(): integer;
procedure setwidth(w: integer);
function getwidth(): integer;
procedure draw;
end;
var
{
r1 is a reference to a Rectangle class instance
}
r1: Rectangle;
{
We need a constructor for the class. Create is "standard". Mostly!
}
constructor Rectangle.create(h, w: integer);
begin
{
We can just assign the passed values to height and
width, but we would like to carry out some validation
to keep them withing acceptable bounds.
}
setheight(h);
setwidth(w);
end;
{
We have a few functions to help set stuff.
}
procedure Rectangle.setheight(h: integer);
begin
if (height < minHeight) then
height := minHeight
else
height := h;
end;
procedure Rectangle.setwidth(w: integer);
begin
if (width < minWidth) then
width := minWidth
else
width := w;
end;
{
We have a few functions to help get stuff.
}
function Rectangle.getheight(): integer;
begin
getheight := height;
end;
function Rectangle.getwidth(): integer;
begin
getwidth := width;
end;
{
And a few procedures to draw a rectangle. I say "draw"....
}
procedure Rectangle.drawTopBottom;
var i: integer;
begin
write('+');
for i := 1 to width - 2 do
write('-');
writeln('+');
end;
procedure Rectangle.drawMiddle;
var i, j: integer;
begin
for i := 1 to height - 2 do
begin
write('|');
for j := 1 to width - 2 do
write(' ');
writeln('|');
end;
end;
procedure Rectangle.draw;
begin
{ Top line. }
drawTopBottom;
{ Middle of rectangle. }
drawMiddle;
{ Bottom line. }
drawTopBottom;
end;
{
The actual program starts here.
We create a new rectangle and assign it to r1, it gets its
width and height from the constructor. After drawing it,
change the width and height and draw the new rectangle.
}
begin
{
This will be adjusted to 2 by 2. Minimum sizes apply.
}
r1:= Rectangle.create(1, 1);
writeln(' Draw Rectangle: ', r1.getheight(), ' by ' , r1.getwidth());
r1.draw;
r1.setheight(5);
r1.setwidth(7);
writeln(' Draw Rectangle: ', r1.getheight(), ' by ' , r1.getwidth());
r1.draw;
r1.setwidth(10);
writeln(' Draw Rectangle: ', r1.getheight(), ' by ' , r1.getwidth());
r1.draw;
end.
Code: Select all
Draw Rectangle: 2 by 2
++
++
Draw Rectangle: 5 by 7
+-----+
| |
| |
| |
+-----+
Draw Rectangle: 5 by 10
+--------+
| |
| |
| |
+--------+
Press any key to exit.
Cheers,
Norm.