Category: OOABAP

  • Class Method in SAP OOABAP

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    A method defines the behaviour of an object. It can access all the attributes and hence can change the status of the object. In this article we will discuss Class Method in SAP OOABAP.

    There are a few points to consider while declaring the method:

    • The method definition is defined in the class definition and implemented in class implementation.
    • It can be declared using Method and End method statement.
    • Methods have parameter interface to pass the values when they are called and return the value to the caller.

    Syntax

    The method must be declared between the statements METHOD and END METHOD.

    METHOD <method-name>.

    .

    .

    END METHOD.

    Types

    There are three types of methods:

    • Instance method

      These methods are declared using METHOD statements. They can access all the attributes of the class and can trigger all the events.

    • Static methods

      These types of method are declared using CLASS-METHOD statements. They can access the static attributes and can trigger static events only.

    • Special methods

      There are two special methods : constructor and class_constructor, which are called automatically whenever the class is accessed for the first time.

    ME Operator in Class Method

    In the implementation part of the instance method in a class, an implicitly created local reference variable ME is available. It points to the currently executed instance. The me variable is reserved and cannot be used for naming attributes and parameter.

    Example

    ****class definition****
    
    CLASS zdemo DEFINITION.
    
           PUBLIC SECTION.
    
                 DATA var(50) TYPE C VALUE “Displaying me variable”.
    
                    METHOD instance_method.                                                        “Instance Method definition
    
                    CLASS-METHODS static_method.                                              “Static Method definition
    
    END CLASS.
    
    ****class implementation****
    
    CLASS zdemo IMPLEMENTATION.
    
           METHOD instance_method.                                                                “Instance Method implementation
    
                    WRITE : ME->var.                                                                             “ Displaying ME Variable
    
                    WRITE : “This is instance method”
    
           END METHOD.
    
           METHOD static_method.                                                                      “Static Method implementation
    
                    WRITE : “This is static method”
    
           END METHOD.
    
    END CLASS.
    
    ****creating class object****
    
    START-OF-SELECTION
    
    DATA : object_demo TYPE REF TO zdemo.
    
    CREATE OBJECT object_demo.
    
    CALL METHOD : object_demo-> instance_method ,
    
                                    object_demo->static_method.

    Class Method

  • Objects in ABAP

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    Objects in ABAP are special variables that have distinct characteristics and behaviors in general terms known as attributes and methods. The attributes define the state of an object and a method defines the behavior or actions performed by the object.

    An object has three main characteristics-

    • State – State defines the set of attributes and its values.
    • Identity – Each object has a unique identity.
    • Behaviour – Behaviour defines the actions performed.

    The two objects may have the same state or behaviour but their identity is always unique. The identity of object sustains till its lifetime.

    For example, a student has attributes like student name (first name, last name), student id, date of birth, address and behaviour would be the change in its attributes. The two students may have the same attributes and behaviour but they are not identical. Their identity is unique and will never change throughout their lifetime.

    Objects interact with each other by sending messages.

    Definition

    An object is the instance of the class. It is a special variable that has distinct characteristics and behaviours.

    ABAP Objects creation

    Object creation includes two steps. They are as follows:

    • Creating reference variable to class.

    DATA : <object_name> TYPE REF TO <class_name>.

    • Creating an object from the reference variable.

    CREATE OBJECT : <object_name>.

    Example

    Let’s jot down an example.

    ****class definition****
    
    CLASS zdemo DEFINITION.
    
                    PUBLIC SECTION.
    
                                     METHOD : zdemo_method.
    
    END CLASS.
    
    ****class implementation****
    
    CLASS zdemo IMPLEMENTATION.
    
                    METHOD zdemo_method.
    
                                    WRITE : “ABAP Object”
    
                    END METHOD.
    
    END CLASS.
    
    ****creating class object****
    
    START-OF-SELECTION.
    
    DATA : object_demo TYPE REF TO zdemo.                                             “Creating reference variable”
    
    CREATE OBJECT object_demo.                                                                   “Creating object”
    
    CALL METHOD : object_demo->zdemo.

    Objects in ABAP

    In the example, zdemo_method is the method defined in the public section of definition part of the class zdemo. The implementation part of the method is provided in the class implementation. Firstly, we have created the reference variable object_demo to the class and then created an object object_demo from the reference variable. The object_demo->zdemo calls of the method zdemo_method and executes the code inside the method.

  • Class Constructor in a Class

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    We have understood about constructors in our previous article, a constructor is a special method that is invoked automatically at the time object is created or instantiated. It has two types: Instance Constructor and Static Constructor. The static constructor also called as class constructor is invoked whenever there is first call to the class whether it is through an instance or class.

    The class constructor has some special properties like,

    • Each class has a single static constructor.
    • The class constructor is called exactly once for each class.
    • The method don’t have importing/ exporting parameters and cannot raise exception.

    The class constructor can also be used to set default values for global attributes irrespective of the instance or methods. Also, while declaring the class constructor one must keep in mind that the name of the constructor must be CLASS_CONSTRUCTOR and declared using the statement CLASS-METHODS in the declaration part of the class.

    Definition

    A class constructor is a method which is automatically invoked whenever the first call to the class is made, it may be through an instance or class.

    Example

    Let us look into an example:

    **** Class Definition****

    CLASS  ZCL_DEMO DEFINITION.

    PUBLIC SECTION.

    METHODS:  CONSTRUCTOR.                                                         “Instance Constructor”

    CLASS-METHODS: CLASS_CONSTRUCTOR.                              “Static Constructor”

    END CLASS.

    ****Class Implementation****

    CLASS  ZCL_DEMO IMPLEMENTATION.

    METHOD CONSTRUCTOR.

    WRITE: “Instance Constructor is initiated”.

    END METHOD.

    METHOD CLASS_CONSTRUCTOR.

    LV_DATE = SY-DATUM.                                                                  “Changing the value of attribute”

    END METHOD.

    END CLASS.

    START-OF-SELECTION.

    DATA: LO_DEMO TYPE REF TO ZCL_DEMO.

    **Class object creation**

    CREATE OBJECT LO_DEMO.

    **Whenever the first call to class is made CLASS_CONSTRUCTOR  is triggered

    WRITE: “INSTANTIATING CLASS CONSTRUCTOR”, ZCL_DEMO=>LV_DATE.

     

    A commonly asked question is that whether we can redefine the constructors? So, it is a big NO as the redefinition of constructors are not allowed and the program will fall into error “Constructor may not be over-defined”.

  • Message Class in SAP ABAP (SE91): Create & Use Examples

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    To issue a message or warning or error or any kind of information in ABAP, either we have to hard code that message or maintain it in text symbols. What if the same message is required somewhere else like in any other program or class, again hard coding it or maintaining in text symbol would be recurring and inefficient procedure.

    Instead of doing this, we can collect all the messages at one place and use it multiple times and at multiple places, that one place is nothing but a message class. Any message can be identified with a unique number assigned to it. To use a message from message class in any ABAP program or in any class, we only need to specify the message class, message number and message type.

    Definition

    Message Class is like a container which contains all messages in it. All the messages from different message classes are stored in database table T100.

    Message Class Creation

    A message class can be created in two ways:

    1. Through transaction code SE91.

     

    Message class creation through T-Code SE91
    Message class creation through T-Code SE91

     

    Message class Maintenance Screen
    Message class Maintenance Screen
    • Syntax of calling these messages from message class in ABAP Programs:

            MESSAGE <type of message><message number>(message class name) WITH <parameter>.

    Example 1 : MESSAGE I000(ZTEST_CLASS).                                                     “Information Message

    Example 2 : MESSAGE E0001(ZTEST_CLASS) WITH 0001.                                     “Error Message

    Note: In figure 2, message text at 001 position is having ‘&’. With this operator we can pass text/literals whatever we want to display. So, for example 2 message will get displayed as:

     ‘The value 0001 is invalid’.

    1. Through report.

    Syntax : REPORT <Report Name> message-id <Message Class>

    “Double click on message class name to create a message class.

    Advantages

    A single message can be used multiple times at multiple places, we don’t need to hard code same message or maintain the same text symbols in different programs.

  • SAP ABAP Unit Testing Class

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    ABAP unit testing is a methodology for software development. Whenever we create a class, it is mandatory to create its test class to check the behavior of our code if it is working exactly as it was expected.  While developing any object, it helps the developer to cover all possible scenarios. With ABAP unit test class, we can also check the coverage of code lines.

    Definition

    ABAP unit test class provides a methodology to test the individual source of code to determine if they are fit to use.

    The global class CL_UNIT_ASSERT contains a method that can be used for testing, the following are the most common methods:

    1. ASSERT_EQUALS – Checks the equality of two data objects.
    2. ASSERT_DIFFERS – Checks for the difference between two data objects.
    3. ASSERT_BOUND – Checks for the validity of the reference of a reference variable.
    4. ASSERT_INITIAL – Checks whether the reference of a reference variable is invalid.
    5. ASSERT_NOT_INITIAL – Checks whether the data object is not having its initial value.
    6. ASSERT_SUBRC – Checks for the specific value of SY-SUBRC.

    Program

    Below is a method ‘GET_ORDER_DATA’ of class ‘ZCL_PROD_ORD_TEST ‘  to fetch the operation details from the production order.

    Note: Local Test Class will get generated automatically through test class generation wizard.

    Method get_order_data

    Figure 1: Method get_order_data

    OSQL test double Framework : To remove the dependency from database tables.

    Unit Test Class

    Figure 2 : Unit Test Class

    Mocking virtual database tables to test the behavior of code.

    Unit Testing of Method GET_ORDER_DATA

    Figure 3: Unit Testing of Method GET_ORDER_DATA

    Advantages

    1. ABAP Unit provides excellent support for test-driven development in ABAP.
    2. You can run tests quickly and easily right from the development environment.
    3. You can navigate back and forth between a test class and the production code.
    4. With ABAP Unit test class, there is no such dependency on availability on test data to test the functionality.
    5. Fewer bugs reported with ABAP unit testing and less time wasted.
  • Exception Class in SAP ABAP

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    To understand an exception class, we need to understand what is an exception and when it is raised.

    When we execute any program, some discrepancies can occur due to which a normal flow of execution gets interrupted and the behavior will not be the same as it was expected. That discrepancy is like an event which is occurring due to some reason, which is known as an ‘Exception’.

    It is required to handle such discrepancies in order to prevent the execution flow of any program. In order to achieve that, SAP ABAP has a special class known as an ‘Exception Class’.

    Exception Classes can be defined in a global class as well as in a local class. There are three exception classes exists, which are the subclasses of one root class ‘CX_ROOT’. Those three exception classes are:

    1. CX_STATIC_CHECK – which is being checked by both compiler and runtime system.
    2. CX_DYNAMIC_CHECK – Checked only at runtime system. All System exceptions will come under this exception.
    3. CX_NO_CHECK – This type will be chosen if exceptions are frequent.

    Definition

    An Exception class is used to handle the discrepancies(exception) occurs during the execution a of program.

    Whenever an exception occurs, an object is created (known as an exception object). The attributes of this object would contain information about the error. This exception can be caught by using TRY….CATCH…..ENDTRY block.

    TRY….ENDTRY block contains a protected area, where an exception can be caught using the CATCH statement. One TRY….ENDTRY block can catch more than one exception, but it should get caught in a sequence in which it occurs.

    There are two types of exception handling cases:

    1. One where the exception was raised, deleted before or after handling it.
    2. The other, where an exception which was raised is retained and the program is resumed after the statement that raised an exception.

    Program

    Let’s take an example of a simple arithmetic operation of two numbers. An exception should be raised if one of the two operands is missing.

    NOTE: A local class is used in below sample program.

    REPORT ztest_exception.

    CLASS lcx_missing_operand DEFINITION

    INHERITING FROM CX_STATIC_CHECK.

    ENDCLASS.                                                 “lcx_missing_operand  DEFINITION

     

    CLASS lcl_test_exception DEFINITION.

    PUBLIC SECTION.

    METHODS: add_numbers IMPORTING iv_num1 TYPE i OPTIONAL

    iv_num2 TYPE i OPTIONAL

    RETURNING VALUE(rv_calc) TYPE i

    RAISING   lcx_missing_operand

    PRIVATE SECTION.

    METHODS: do_check RAISING  lcx_missing_operand.

    DATA: lv_num1 TYPE i,

    lv_num2 TYPE i,

    lv_result TYPE i.

    ENDCLASS.                                                      “lcl_test_exception DEFINITION

     

    CLASS lcl_test_exception IMPLEMENTATION.

    METHOD add_numbers.

    v_num1 = iv_num1.

    v_num2 = iv_num2.

    me->do_check( ).

    rv_calc = v_result.

    ENDMETHOD.

     

    METHOD do_check.

    IF v_num1 IS INITIAL.

    RAISE EXCEPTION TYPE lcx_missing_operand.

    ENDIF.

    ENDMETHOD.

     

    ENDCLASS.                                                      “lcl_test_exception IMPLEMENTATION

     

    START-OF-SELECTION.

    DATA: lo_obj TYPE REF TO lcl_test_exception.

    DATA: lo_exc_root TYPE REF TO CX_ROOT.

    DATA: lv_msg TYPE STRING.

    CREATE OBJECT lo_obj.

    TRY .

    lo_obj->add_numbers( iv_num1 = 10 ).

    CATCH lcx_missing_operand.

    WRITE: /  ‘Operand is missing’.

    CATCH CX_ROOT INTO lo_exc_root.

    lv_msg = lo_exc_root->get_text( ).

    WRITE: / lv_msg.

    ENDTRY.

    Advantages

    1. With exception classes, you can track the sequence of called methods. Since in exception class, we have try-end-try block, so we can put the called methods in it, to know if one of them get failed.
    2. An exception class has an advantage that non-OO programmers won’t understand your code, increasing your job security a little.
  • Local Classes in SAP ABAP

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    One of the flavors of ABAP classes (Global Classes) we have already discussed in the last article. Another flavor of ABAP class are Local Classes. The only difference between a local class & global class is visibility & accessibility. A local class can be accessed within that program only in which it is being defined & implemented, whereas a global class can be accessed in any other program.

    NOTE: In some of the previous articles, where different types of classes have been described, there the sample programs were the examples of local class only.

    Definition

    A class which is defined and implemented in a program is known as Local Class. Local classes in SAP ABAP can be created through Transaction code SE-38(tool to create a report).

    Program

    Let’s take an example of this class ‘ZCL_MARA’. This class is having one method ‘GET_MATERIAL_TYPE’  to get the material type of a given material.

    NOTE: ‘MARA’ is a table in SAP ABAP for general material data. So, in this sample program, material (iv_matnr – importing parameter of a method) is given by the user, and this method will fetch the material type ( like finished, semi-finished, raw, etc. )

    TYPES: BEGIN OF ty_mara,                                       “USER-DEFINED TYPES

    Matnr TYPE mara-matnr,

    Mtart TYPE mara-mtart,

    END OF ty_mara.

    CLASS zcl_mara DEFINITION.

    PUBLIC SECTION.

    METHODS: get_material_type

    IMPORTING iv_matnr TYPE mara-matnr

    EXPORTING ls_mara type ty_mara.

    ENDCLASS.                                                                    “CLASS DEFINITION

     

    CLASS zcl_mara IMPLEMENTATION.

    METHOD get_material_type.

    SELECT SINGLE matnr, mtart FROM mara INTO ls_mara

    WHERE matnr = iv_matnr

    ENDMETHOD.

    ENDCLASS.                                                                   “CLASS IMPLEMENTATION

     

    Advantages

    1. To restrict the usage of any functionality, we can use it in a local class of any program.
    2. A Local class is very useful while creating an ABAP Unit Test Class, as a local test class has been generated within a global class.
    3. These classes are useful for the enhancements of class methods.
  • Super Class in SAP ABAP

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    One of the three pillars of OOABAP uses this concept of Super class to achieve ‘Inheritance’. Super class allows us to extend that class by creating a subclass of it. This subclass will have all the properties of a super class, plus it can have additional properties as well.

    Definition

    A class which is having a derived class from it, is known as a ‘Super Class’.

    To make a class Super Class, the first step is to uncheck the box indicating Final Class while creating a Class through T-Code SE24 (Class Builder). Because if a class is creating as a Final cannot be extended further, and inheritance cannot be achieved in that case.

    If the developer is using this concept of the super class & subclass, then he/she can have all the advantages of ‘Inheritance’.

    Program of Super Class in SAP ABAP:

    Let’s take an example of this employer class ‘ZCL_EMPLOYER’. This employer class is having one method ‘GET_INCOME’ to get income.

     

    CLASS zcl_employer DEFINITION.

    PUBLIC SECTION.

    METHODS: get_income RETURNING VALUE(income) TYPE F.

    PRIVATE SECTION.

    DATA: income TYPE F VALUE 100.

    ENDCLASS.                                                                    “CLASS DEFINITION

    CLASS zcl_employer IMPLEMENTATION.

    METHOD get_income.

    income = me->income * 80.

    ENDMETHOD.

    ENDCLASS.                                                                   “CLASS IMPLEMENTATION

     

    Now, I want to create a subclass of it, where I want to redefine this method ‘GET_INCOME’.

     

    CLASS zcl_manager DEFINITION INHERITING FROM zcl_employer.

    PUBLIC SECTION.

    METHODS: get_income REDEFINITION.

    PRIVATE SECTION.

    DATA: income TYPE F VALUE 100.

    ENDCLASS.                                                                    “CLASS DEFINITION

    CLASS zcl_manager IMPLEMENTATION.

    METHOD get_income.

    income = me->income * 100.

    ENDMETHOD.

    ENDCLASS.                                                                   “CLASS IMPLEMENTATION

     

    Once you derived a class from another class, the new class will be known as ‘SUBCLASS’ or ‘CHILD CLASS’. And the class from which a new class is deriving will be known as ‘SUPER CLASS’ or ‘PARENT CLASS’.

    As discussed earlier, the subclass can have all the properties, & methods of a super class. The developer can redefine the existing methods of the super class and he/she can also add some new functionality into it.

    Advantages:

    Provides reusability of code functionality & fast implementation time. It can have all the advantages of ‘Inheritance’.

  • Global Class in SAP ABAP

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    From the reference of an article: SAP ABAP Classes we have discussed the flavors of ABAP Classes & we came to know that ABAP classes are available in two flavors, one of which is Global Class.

    The visibility section of the global class is always public, meaning all the ABAP programs in an R/3 system can access the global class. However, instantiation of that class could be set as either public, protected or private.

    Definition

    A class which is defined in the class builder (Transaction Code – SE24) is known as Global Class.

    While creating a class from Class Builder (T-code: SE24), we get many options that indicate which type of global class we want to create, for example, usual ABAP class, exception class, persistent class or a test class. It also gives an option of whether we want to make it final or not.

    After selecting the type of class and properties ( description & instantiation ), a screen will come where we can see the components of a global class like:

    1. Interfaces – Independent structures which are used in a class to extend the functionality of a class.
    2. Friends – If there is any class, which you want to make a friend of your class, you can define it here.
    3. Attributes – variables or constant declared within the class and can be accessed by all the methods of that class.
    4. Methods – Determines the behavior of an object, it provides some functionality. A method is allowed to access all the attributes of their class.
    5. Events – A mechanism through which one method can raise method of another class.
    6. Types – Table Types can be defined here, that can further be used anywhere in the whole class.
    7. Alias – A concept of providing an alternate method name for an interface method in an implemented class.

     

    While defining an attribute and method, there are two mandatory fields, which we need to provide:

    1. Level: We have 2 level options:
    • Instance – Components declared as instance can only be addressed by the instance(object) of that class only.
    • Static – Components declared as static can be used independently of a class instance.
    1. Visibility: We have 3 Visibility options:
    • Public – Components with this visibility will be available to all.
    • Protected – Components will be visible to that class, where they are defined and to the inherited class.
    • Private – Components will be visible to that class only, where they are defined.

     

    Advantages:

    Provides reusability of code functionality & fast implementation time.

  • Singleton Class in ABAP

    Preface – This post is part of the Object Oriented ABAP series.

    Introduction

    Sometimes there is a need to instantiate an object at a time, that means only one instance is required at one point of time. This is a very common requirement while designing an application. To achieve such a scenario, there is one concept of ‘Singleton Pattern’ or ‘Singleton Class’ in OOABAP.

    This was the theoretical part. Now, a question comes, that how to achieve it in real? So, here the answer is: By declaring the constructor as a ‘Private’ one.  This private constructor can be created after changing the instantiation type to private. This helps us to restrict the further creation of an object of a class.

    Definition of Singleton Class in ABAP

    A class is said to be a singleton class if it can have the utmost one instance only.

    Following is a procedure to create a singleton class :

    1. Visibility of class should be private.
    2. Declare a private attribute with reference to the same class, in which it is being declared.
    3. Create a public static method with returning parameter, having a reference of the same class.
    4. Create an implementation and an object inside the implementation of a public static method.
    5. To create an instance for the singleton class, call this public static method in any program.

    Program:

    For the better understanding of this Singleton Concept, let’s consider this below sample program and here as you can see that object creation of a singleton class is not possible outside the class. So, this is how a singleton pattern works.

    Singleton Class in ABAP
    Singleton Class in ABAP – Image Illustration

    Program Explanation:

    In the above program, we have implemented a local class lcl_singleton_test inside an ABAP Report. In the class definition, we have kept the class as private and have declared a Public section. Under the public section, we have  declared a static attribute lo_singleton which refers to the program itself. Also, we have defined a local variable v of type integer. Then, we have defined the class constructor and a method set_name for the class.

    Later, we have implemented the class where we are creating an object under class constructor. Also, we have assigned a value i.e. “GEETANSHU” to the local variable v.
    Now, in the report code, we are doing a static call to our class via its object r1.

    Advantages of Singleton Class in ABAP:

    1. With the use of Singleton class, testability improves.
    2. Singleton pattern supports the main moto of Object Oriented Design principle by allowing it to open for enhancements and closed for modifications.
    3. The advantage of using a private constructor in Singleton class (as no one create an object of your class).