Sunday, June 23, 2024

Abap new

ABAP NEW Keyword

ABAP NEW Keyword: Simplifying Object Creation

The NEW keyword in ABAP is a powerful addition that simplifies the creation of objects and data instances. It is part of the newer ABAP syntax introduced to make the code more readable and concise. Here, we explore how to use NEW with several examples.

Creating Objects with NEW

DATA(lo_object) = NEW cl_example_class( ).

You can also pass parameters directly to the constructor:

DATA(lo_object) = NEW cl_example_class( iv_param = 'Value' ).

Creating Structures with NEW


TYPES: BEGIN OF ty_structure,
         field1 TYPE i,
         field2 TYPE c LENGTH 10,
       END OF ty_structure.

DATA(ls_structure) = NEW ty_structure( field1 = 1 field2 = 'Hello' ).
    

Full Example


CLASS cl_example DEFINITION.
  PUBLIC SECTION.
    DATA: iv_param TYPE string.
    METHODS: constructor IMPORTING iv_param TYPE string.
ENDCLASS.

CLASS cl_example IMPLEMENTATION.
  METHOD constructor.
    me->iv_param = iv_param.
  ENDMETHOD.
ENDCLASS.

TYPES: BEGIN OF ty_structure,
         field1 TYPE i,
         field2 TYPE c LENGTH 10,
       END OF ty_structure.

DATA: lo_object TYPE REF TO cl_example,
      lt_table TYPE TABLE OF ty_structure,
      ls_structure TYPE ty_structure.

lo_object = NEW cl_example( iv_param = 'Hello World' ).
lt_table = NEW TABLE OF ty_structure WITH EMPTY KEY.
ls_structure = NEW ty_structure( field1 = 100 field2 = 'Sample' ).

WRITE: / lo_object->iv_param,
       / ls_structure-field1,
       / ls_structure-field2.
    

Conclusion

The NEW keyword enhances ABAP by making object and data creation more intuitive and less verbose. It's a simple yet powerful tool that can make your code cleaner and more efficient.

ABAP Inline Declarations: A Byte-Sized Guide with Examples

ABAP Inline Declarations ABAP Inline Declarations ABAP inline declarations are a feature intr...