![]()
|
Extending classesIt's common, when dealing with objects, to take an existing class and extend it. One way to do this is to modify the source code of the original class – but this isn't always available, and with many different people modifying a class, classes could rapidly get over-complicated.Languages that deal with objects, like NetRexx, therefore allow new classes of objects to be set up which are derived from existing classes. For example, if you wanted a different kind of Oblong in which the Oblong had a new property that would be used when printing the Oblong as a rectangle, you might define it thus: /* charOblong.nrx -- an oblong class with character */ class charOblong extends Oblong printchar -- the character for display /* Constructor to make a new oblong with character */ method charOblong(newwidth, newheight, newprintchar) super(newwidth, newheight) -- make an oblong printchar=newprintchar -- and set the character /* 'Print' the oblong */ method print loop for super.height say printchar.copies(super.width) endThere are several things worth noting about this example:
The charOblong.nrx file is compiled just like Oblong.nrx was, and should create a file called charOblong.class. Here's a program to try it out: /* trycharOblong.nrx -- try the charOblong class */ first=charOblong(5,3,'#') -- make an oblong first.print -- show it first.relsize(1,1).print -- enlarge and print again second=charOblong(1,2,'*') -- make another oblong second.print -- and print itThis should create the two charOblong objects, and print them out in a simple ‘character graphics’ form. Note the use of the method relsize from Oblong to resize the charOblong object. Optional argumentsAll methods in NetRexx may have optional arguments (omitted from the right) if desired. For an argument to be optional, you must supply a default value. For example, if the charOblong constructor was to have a default value for printchar, its method instruction could have been written:method charOblong(newwidth, newheight, newprintchar='X')which indicates that if no third argument is supplied then 'X' should be used. A program creating a charOblong could then simply write: first=charOblong(5,3) -- make an oblongwhich would have exactly the same effect as if 'X' were specified as the third argument. [previous | contents | next] From
The NetRexx Language by
Mike Cowlishaw,
|