Give an object a valid starting state

A tracker without a tracking code is not useful. An instance constructor runs when an object is created and can receive the values needed to establish that object’s initial state.

Instance constructor

CLASS lcl_tracker DEFINITION.
  PUBLIC SECTION.
    DATA tracking_code TYPE string.
    METHODS constructor IMPORTING iv_tracking_code TYPE string.
ENDCLASS.

CLASS lcl_tracker IMPLEMENTATION.
  METHOD constructor.
    tracking_code = iv_tracking_code.
  ENDMETHOD.
ENDCLASS.

DATA(tracker) = NEW lcl_tracker( iv_tracking_code = 'PK-204' ).

In a real class, keep the attribute private and validate the input before storing it. The constructor should make it difficult to create an object in a state that later methods cannot handle.

Class constructor is different

CLASS_CONSTRUCTOR is called automatically before the class is first accessed in the relevant internal session. It has no importing parameters and should not be used as a general setup hook for every object. Avoid putting business workflows, user-specific state, or unpredictable external work there.

Choosing initialization alternatives

Use the instance constructor for required object-specific dependencies or values. Use ordinary factory methods when creation needs named choices, validation results, or a more expressive API. Avoid a public attribute that callers must remember to populate after construction.

Practice

Add a constructor importing iv_tracking_code, store it, instantiate the class with PK-204, and set result from the created object. Add the selected mode’s output. This checker does not activate or run ABAP.

Version note: Constructor syntax and API restrictions depend on the target ABAP language version.

Sources

Developer practice · ABAP

Practice: validate a parcel at creation

Define a constructor that receives a tracking code and stores it in the object, then create a tracker and copy its code to result.

Choose your ABAP environment

This choice changes the output pattern checked here: WRITE belongs in a classic executable report, while out->write( ) uses the supplied output reference in an ABAP Cloud class-run method. It does not switch the language version of the other code; check release and API availability in your target system.

Complete the task and include the output statement shown for your selected environment. Variable names can differ if you use them consistently. This browser checker checks structure only; it does not compile or run ABAP.

0 required structures detected · 0 checks