Creating an object instance is a two-step process: declare a variable of the object type, then initialize it by calling a constructor method.
Declare an object variable
object obj_type| Element | Description |
|---|---|
object | The identifier assigned to the object variable |
obj_type | The identifier of the previously defined object type |
Initialize with a constructor method
After declaring the variable, call a constructor method to assign initial values to its attributes:
[NEW] obj_type ({expr1 | NULL} [, {expr2 | NULL} ] [, ...])| Element | Description |
|---|---|
obj_type | The constructor method name, which matches the object type name |
expr1, expr2, ... | Expressions type-compatible with the first, second, and subsequent attributes of the object type. If an attribute is itself an object type, pass NULL, an object initialization expression, or any expression that returns that object type |
NEW | Optional keyword that invokes the constructor whose signature matches the provided parameters |
Examples
Declare and initialize in the block body
DECLARE
v_emp EMP_OBJ_TYPE;
BEGIN
v_emp := emp_obj_type( -- call the constructor for EMP_OBJ_TYPE
9001,
'JONES',
addr_obj_type('123 MAIN STREET', 'EDISON', 'NJ', 08817) -- nested constructor for address attribute
);
END;v_emp is declared as EMP_OBJ_TYPE. The block body initializes it using the emp_obj_type constructor. The third argument uses a nested addr_obj_type constructor to supply the address attribute.
Initialize at declaration and use NEW in the block body
DECLARE
mgr EMP_OBJ_TYPE := (9002, 'SMITH', NULL); -- initialized at declaration
emp EMP_OBJ_TYPE;
BEGIN
emp := NEW EMP_OBJ_TYPE(9003, 'RAY', NULL); -- NEW invokes the matching constructor
END;mgr is initialized directly in the declaration. emp is declared without a value and assigned using NEW in the block body.
Alternate syntax (PolarDB for PostgreSQL compatible with Oracle)
PolarDB for PostgreSQL (compatible with Oracle) supports an alternate syntax in place of the constructor method:
[ ROW ] ({ expr1 | NULL } [, { expr2 | NULL } ] [, ...])ROW is optional when two or more expressions are provided. If only one expression is specified, ROW is required.