The _NEW_ operator also
enables you to create an instance of a class and to run a class constructor.
A
constructor is a method that is automatically
invoked whenever an object is instantiated. You can use a constructor
to initialize the object to a valid starting state. The method that
is used as the constructor of a class has the same name as the class.
You can specify a signature with no arguments to override the default
constructor (that is, its signature is ()V), or you can overload the
constructor with signatures that use one or more arguments. You cannot,
however, specify a return type.
Consider a class that
is defined as follows:
class sasuser.test.Account
extends sashelp.fsp.object.class;
/* attributes */
public num accountNumber;
public num balance;
/* constructor */
Account: public method
id:input:num;
accountNumber=id;
balance=0;
endmethod;
endclass;
When an Account object is instantiated, the
constructor assigns a specific number as the
accountNumber
and initializes the
balance
attribute
to 0. For example:
import sasuser.test.Account.class;
dcl account newAccount = _new_ account(1234);
The _NEW_
operator calls the account constructor method and passes a value 1234
to its numeric argument. This creates a new Account object that has
1234 as its accountNumber and a balance of 0.
You can also overload
the constructor to accept a different number of arguments. Consider
a subclass of the Data Set List Model class:
class sasuser.myclasses.ourData
extends sashelp.classes.datasetlist_c.class;
OurData: public method
lib:char;
/* library is an inherited attribute */
if lib ne ''
then library=lib; /* set library attribute */
endmethod;
OurData: public method
lib:char
level:num;
/* library and levelCount are inherited attributes */
if lib ne ''
then library=lib; /* set library attribute */
if level in (1,2)
then levelCount=level; /* set levelCount attribute */
endmethod;
endclass;
You can pass one argument to the _NEW_ operator
to call the constructor with one argument in its signature. In the
following example, the constructor initializes the
library
attribute:
import sasuser.test.OurData.class;
dcl OurData table = _new_ OurData('sasuser');
You could
also pass two arguments to the _NEW_ operator to call the constructor
with two arguments in its signature. In the following example, the
constructor sets the
library
and
typeFilter
attributes:
import sasuser.test.OurData.class;
dcl OurData table = _new_ OurData('sasuser',1);
Because
the
library
attribute of the table
object is initialized in both cases, you can immediately query
table.items
to retrieve the list of SAS tables in
the specified library. If
typeFilter
is 1, then the
items
list contains
only the names of the tables and not the full two-level SAS name.
For complete information
on the _NEW_ operator and constructors, see the
SAS Component
Language: Reference.