OOP ABAP
ABAP DevelopmentIntermediate

Instance Methods, Static Methods and Constructors

Understand object creation, constructor logic, instance methods and static methods.

Explanation

An instance method is called using an object reference and can work with instance attributes. A static method belongs to the class itself and can be called without creating an object. Constructors are special methods that run when an object is created. They are useful for setting mandatory initial values or dependencies. Static methods are useful for pure utility logic, but overusing static methods can make code harder to test and extend. In real projects, service classes often use constructors to receive configuration or dependencies, while utility classes may expose static helper methods.

Code example

ABAP Code
CLASS lcl_pricing_service DEFINITION.  PUBLIC SECTION.    METHODS constructor      IMPORTING iv_vkorg TYPE vkorg.    METHODS get_sales_org      RETURNING VALUE(rv_vkorg) TYPE vkorg.    CLASS-METHODS is_high_value      IMPORTING iv_amount TYPE netwr      RETURNING VALUE(rv_high) TYPE abap_bool.  PRIVATE SECTION.    DATA mv_vkorg TYPE vkorg.ENDCLASS. CLASS lcl_pricing_service IMPLEMENTATION.  METHOD constructor.    mv_vkorg = iv_vkorg.  ENDMETHOD.   METHOD get_sales_org.    rv_vkorg = mv_vkorg.  ENDMETHOD.   METHOD is_high_value.    rv_high = xsdbool( iv_amount > 100000 ).  ENDMETHOD.ENDCLASS. START-OF-SELECTION.  DATA(lo_service) = NEW lcl_pricing_service( '1000' ).  WRITE: / lo_service->get_sales_org( ).   IF lcl_pricing_service=>is_high_value( 150000 ) = abap_true.    WRITE: / 'High value order'.  ENDIF.

Real project scenario

A pricing service class receives sales organization in the constructor. All later pricing checks use that sales organization without passing it again to every method.

Common mistakes

- Using static methods for everything. - Putting database-heavy logic in constructors. - Not validating mandatory constructor input. - Confusing instance attributes with static attributes.

Best practices

- Use constructors for mandatory setup. - Use instance methods for object-specific state. - Use static methods for stateless helper logic. - Avoid heavy processing inside constructors.

Interview angle

Interviewers may ask when to use static methods. A strong answer says static methods are fine for stateless utility logic, but business services often benefit from instance methods.