Search code examples
oopinterfaceabapnew-operator

Create instance for a class interface in a single line?


Maybe it's a pretty basic question but I didn't manage to find out if it's possible or not.

Since 7.40, we have the NEW operator to create instances. It allows to create an object and call a method in a single line:

DATA(result) = NEW zclass( )->method( ).

But if my zclass implements a zinterface, I would like to do the following in a single line:

DATA: zif_instance TYPE REF TO zinterface.
zif_instance = NEW zclass( ).
DATA(result) = zif_instance->method( ).

Is it possible?


Solution

  • There can be three answers.

    Either you use the interface component selector ~:

    DATA(result) = NEW zclass( )->zif_instance~method( ).
    

    Or your class defines an alias to the interface method, say method_alias, via the ALIASES statement, i.e. ALIASES method_alias FOR zif_instance~method (NB: the alias could also be the same name as the original method name i.e. method):

    DATA(result) = NEW zclass( )->method_alias( ).
    

    Or you have the CAST operator.

    DATA(result) = CAST zif_instance( NEW zclass( ) )->method( ).