Example 1: Simple INTERFACE usage
Defines an INTERFACE
to handle shape objects.
This first module called
rectangle.4gl
defines the Rectangle
type and the methods that apply to this
type:PUBLIC TYPE Rectangle RECORD
height, width FLOAT
END RECORD
PUBLIC FUNCTION (r Rectangle) area () RETURNS FLOAT
RETURN r.height * r.width
END FUNCTION
PUBLIC FUNCTION (r Rectangle) kind () RETURNS STRING
RETURN "Rectangle"
END FUNCTION
PUBLIC FUNCTION (r Rectangle) setDimensions (w FLOAT, h FLOAT) RETURNS ()
LET r.width = w
LET r.height = h
END FUNCTION
The
circle.4gl
module defines the Circle
type and methods that
apply to this
type:IMPORT util
PUBLIC TYPE Circle RECORD
diameter FLOAT
END RECORD
PUBLIC FUNCTION (c Circle) area () RETURNS FLOAT
RETURN util.Math.pi() * (c.diameter/2) ** 2
END FUNCTION
PUBLIC FUNCTION (c Circle) kind () RETURNS STRING
RETURN "Circle"
END FUNCTION
PUBLIC FUNCTION (c Circle) setDiameter (d FLOAT) RETURNS ()
LET c.diameter = d
END FUNCTION
Next module imports the
rectangle
and circle
modules, and
defines the Shape
interface to group the area()
and
kind()
methods, which both can apply to the Rectangle
and
Circle
types. The totalArea()
code uses the Shape
type, knowing only about the behavior defined by this interface.Note: The
Rectangle.setDimensions()
and Circle.setDiameter()
methods are not
part of the Shape
interface.IMPORT FGL rectangle
IMPORT FGL circle
TYPE Shape INTERFACE
area() RETURNS FLOAT,
kind() RETURNS STRING
END INTERFACE
FUNCTION totalArea(shapes DYNAMIC ARRAY OF Shape) RETURNS FLOAT
DEFINE i INT
DEFINE area FLOAT
FOR i = 1 TO shapes.getLength()
LET area = area + shapes[i].area()
END FOR
RETURN area
END FUNCTION
FUNCTION main()
DEFINE r1 rectangle.Rectangle
DEFINE c1 circle.Circle
DEFINE shapes DYNAMIC ARRAY OF Shape
CALL r1.setDimensions(10,20)
CALL c1.setDiameter(20)
LET shapes[1] = r1
LET shapes[2] = c1
DISPLAY shapes[1].kind(), shapes[1].area()
DISPLAY shapes[2].kind(), shapes[2].area()
DISPLAY "Total:", totalArea(shapes)
END FUNCTION