Show TOC

Generating Factory MethodsLocate this document in the navigation structure

Context

In the definition of an ABAP class, you can add the static create method from the class name. If the class has attributes, a dialog is opened where you can select the attributes that should be instantiated by the create method. Then, in the public section, the definition of this method is added. In addition, an importing as well as a returning parameter that refers to the same class are added.

Example

The car class has the name attribute:

CLASS cl_car DEFINITION. 
 PUBLIC SECTION. 
 PRIVATE SECTION. 
  DATA name TYPE string. 
ENDCLASS. 
 
CLASS cl_car IMPLEMENTATION. 
ENDCLASS.

Procedure

  1. In the definition part, select the name of the class.
  2. In the context menu, choose Quick Fix or use the shortcut (Ctrl 1).
  3. In the Quick Fix dialog box, double-click Generate factory method.

Results

In the definition part, the create method is added. For each selected attribute, the corresponding r_result returning parameter and i_current_speed importing parameter is created.

In the implementation part, the body of the create class-method is added. Here, the r_result returning parameter is created and assigned to the i_name importing parameter.

Example

ABAP class after generating

CLASS cl_car DEFINITION. 
 PUBLIC SECTION. 
  CLASS-METHODS create 
   IMPORTING 
    i_name TYPE string. 
   RETURNING 
    VALUE(r_result) TYPE REF TO cl_car.
 PRIVATE SECTION.
  DATA name TYPE string.
ENDCLASS. 
 
CLASS cl_car IMPLEMENTATION.
  METHOD create 
    CREATE OBJECT r_result.
    r_result->name = i_name.
  ENDMETHOD.
ENDCLASS.