Thursday 30 November 2017

ABAP – Smart Forms



       SAP Smart Forms tool can be used to print and send documents. This tool is useful in developing forms, PDF files, e-mails and documents for the Internet. The tool provides an interface to build and maintain the layout and logic of a form. SAP also delivers a selection of forms for business processes such as those used in Customer Relationship Management (CRM), Sales and Distribution (SD), Financial Accounting (FI) and Human Resources (HR).

The tool allows you to modify forms by using simple graphical tools instead of using any programming tool. It means that a user with no programming knowledge can configure these forms with data for a business process effortlessly.

In a Smart Form, data is retrieved from static and dynamic tables. The table heading and subtotal are specified by the triggered events and the data is then sorted before the final output. A Smart Form allows you to incorporate graphics that can be displayed either as part of the form or as the background. You can also suppress a background graphic if required while taking a printout of a form.

Some examples of standard Smart Forms available in SAP system are as follows:

 SF_EXAMPLE_01 represents an invoice with a table output for flight booking for a customer.

 SF_EXAMPLE_02 represents an invoice similar to SF_EXAMPLE_01, but with subtotals.

 SF_EXAMPLE_03 specifies an invoice similar to SF_EXAMPLE_02, but one in which several customers can be selected in an application program.

Creating a Form


Let’s create a form by using the SAP Smart Forms tool. You will also learn how to add a node in the Smart Form and test the form in this tutorial. Here we begin with creating a copy of the SF_EXAMPLE_01 form. The SF_EXAMPLE_01 form is a standard Smart Form available in the SAP system.

Step 1: Smart Form Builder is the main interface used to build a Smart Form. It is available on the initial screen of SAP Smart Forms. We need to type the 'SMARTFORMS' transaction code in the Command field to open the initial screen of SAP Smart Forms. In this screen, enter the form name, SF_EXAMPLE_01, in the Form field.

Step 2: Select Smart Forms  Copy or click the Copy icon to open the Copy Form or Text dialog box.

Step 3: In the Target Object field, enter a name for the new form. The name must begin with the Y or Z letter. In this case, the name of the form is 'ZSMM1'.


Step 4: Click the Continue icon or press the ENTER key in the Copy Form or Text dialog box so that the ZSMM1 form is created as a copy of the predefined form SF_EXAMPLE_01.

Step 5: Click the Save icon. The name of the form is displayed in the Form field on the initial screen of SAP Smart Forms.

Step 6: Click the Create button on the initial screen of SAP Smart Forms. The ZSMM1 form appears in Form Builder.

Step 7: The first draft page is created with a MAIN window. All the components of the new form are based on the SF_EXAMPLE_01 predefined form. You can just click a node in the Navigation menu to view its content.


Creating a Text Node in the Form


Step 1: Open a form in the change mode of the SAP Form Builder screen and right-click the Main Window option in the First Page node and select Create  Text from the context menu.

Step 2: Modify the text in the Text field to 'My_Text' and the text in the Meaning field to 'Text_Demo'. Enter the text 'Hello TutorialsPoint.....' in the text-editing box in the center frame of


Step 3: Click the Save button to save the node.

Step 4: Activate and test the node by clicking the Activate and Test icons, respectively. The initial screen of Function Builder appears.

Step 5: Activate and test the function module by clicking the Activate and Execute icons. The parameters of the function module are displayed in the initial screen of Function Builder.

Step 6: Execute the function module by clicking the Execute icon. The Print dialog box appears.

Step 7: Specify the output device as 'LP01' and click the Print preview button.



ABAP – Dialog Programming



    Dialog programming deals with the development of multiple objects. All these objects are linked hierarchically to the main program and they are executed in a sequence. Dialog program development makes use of tools in the ABAP workbench. These are the same tools used in standard SAP application development.

Here are the main components of dialog programs:

 Screens
 Module pools
 Subroutines
 Menus
 Transactions


The Toolset



        Dialog programs should be developed by the object browser (transaction: SE80) so that all objects become linked to the main program without having to explicitly point each object. Advanced navigation techniques enhance the process of moving from one object to the other.

       Screens are made up of screen attributes, screen layout, fields and flow logic. The module pool consists of modularized syntax that is placed inside include programs of the dialog program. These modules can be invoked by the flow logic, which is processed by the dialog processor.


Creating a New Dialog Program



Step 1: Within the transaction SE80, select ‘Program’ from the dropdown and enter a Z name for your custom SAP program as ‘ZSCREENEX’.

Step 2: Press Enter, choose ‘With TOP INCL’ and click the ‘Yes’ button.



Step 3: Enter a name for your top include as ‘ZSCRTOP’ and clilck the green tick mark.

Step 4: Within the attributes screen, simply enter a title and click the save button.

Adding a Screen to the Dialog Program


Step 1: To add a screen to the program, right-click on the program name and select the options Create  Screen.

Step 2: Enter a screen number as '0211' and click the green tick mark.


Step 3: In the next screen, enter a short title, set to normal screen type and click the save button on the top application toolbar.

Screen Layout and Adding ‘Hello World’ Text


Step 1: Click the layout button within the application toolbar and the Screen Painter window appears.

Step 2: Add a Text Field and enter some text such as "Hello World".




Creating Transaction

Step 1: To create a transaction code for your program, simply right click on the program name and choose the option Create  Transaction and enter a transaction code as 'ZTRANEX'.




Step 2: Enter the transaction text, program and screen you have just created (ZSCREENEX & 0211), and tick the ‘SAPGUI for Windows’ checkbox in the ‘GUI support’ section.

Executing the Program


Save and activate everything. You can execute the program. As the program executes, the text you entered is displayed on the screen as shown in the following screenshot.




ABAP – Report Programming




       A report is a presentation of data in an organized structure. Many database management systems include a report writer that enables you to design and generate reports. SAP applications support report creation.

A classical report is created by using the output data in the WRITE statement inside a loop. They do not contain any sub-reports. SAP also provides some standard reports such as RSCLTCOP that is used to copy tables across clients and RSPARAM that is used to display instance parameters.

These reports consist of only one screen as an output. We can use various events such as INITIALIZATON & TOP-OF-PAGE to create a classical report, and each event has its own importance during the creation of a classical report. Each of these events is associated to a specific user action and is triggered only when the user performs that action.

Following is a table describing the events and descriptions:




Example
Let's create a classical report. We will display the information stored in the standard database MARA (contains general material data) by using a sequence of statements in ABAP editor.

REPORT ZREPORT2 LINE-SIZE 75 LINE-COUNT 30(3) NO STANDARD PAGE HEADING.
Tables: MARA.
TYPES: Begin of itab,
MATNR TYPE MARA-MATNR,
MBRSH TYPE MARA-MBRSH,
MEINS TYPE MARA-MEINS,
MTART TYPE MARA-MTART,
End of itab.
DATA: wa_ma TYPE itab, it_ma TYPE STANDARD TABLE OF itab.
SELECT-OPTIONS:
MATS FOR MARA-MATNR OBLIGATORY.
INITIALIZATION.
MATS-LOW = '1'.
MATS-HIGH = '500'.
APPEND MATS.
AT SELECTION-SCREEN.
IF MATS-LOW = ' '.
MESSAGE I000(ZKMESSAGE).
ELSEIF MATS-HIGH = ' '.
MESSAGE I001(ZKMESSAGE).
ENDIF. TOP-OF-PAGE.
WRITE:/ 'CLASSICAL REPORT CONTAINING GENERAL MATERIAL DATA
FROM THE TABLE MARA' COLOR 7.
ULINE.
WRITE:/ 'MATERIAL' COLOR 1, 24 'INDUSTRY' COLOR 2, 38 'UNITS' COLOR 3, 53 'MATERIAL TYPE' COLOR 4.
ULINE.
END-OF-PAGE.
START-OF-SELECTION.
SELECT MATNR MBRSH MEINS MTART FROM MARA
INTO TABLE it_ma WHERE MATNR IN MATS.
LOOP AT it_ma into wa_ma.
WRITE:/ wa_ma-MATNR, 25 wa_ma-MBRSH, 40 wa_ma-MEINS, 55 wa_ma-MTART.
ENDLOOP.
END-OF-SELECTION.
ULINE.
WRITE:/ 'CLASSICAL REPORT HAS BEEN CREATED' COLOR 7.
ULINE.
SKIP.

The above code produces the following output containing the general material data from the standard table MARA:



Object Events



     An event is a set of outcomes that are defined in a class to trigger the event handlers in other classes. When an event is triggered, we can call any number of event handler methods. The link between a trigger and its handler method is actually decided dynamically at run-time.

In a normal method call, a calling program determines which method of an object or a class needs to be called. As fixed handler method is not registered for every event, in case of event handling, the handler method determines the event that needs to be triggered.

An event of a class can trigger an event handler method of the same class by using the RAISE EVENT statement. For an event, the event handler method can be defined in the same or different class by using the FOR EVENT clause, as shown in the following syntax:

FOR EVENT <event_name> OF <class_name>.

Similar to the methods of a class, an event can have parameter interface but it has only output parameters. The output parameters are passed to the event handler method by the RAISE EVENT statement that receives them as input parameters. An event is linked to its handler method dynamically in a program by using the SET HANDLER statement.

When an event is triggered, appropriate event handler methods are supposed to be executed in all the handling classes.


Example


REPORT ZEVENT1.
CLASS CL_main DEFINITION.
PUBLIC SECTION.
DATA: num1 TYPE I.
METHODS: PRO IMPORTING num2 TYPE I.
EVENTS: CUTOFF.
ENDCLASS.
CLASS CL_eventhandler DEFINITION.
PUBLIC SECTION.
METHODS: handling_CUTOFF FOR EVENT CUTOFF OF CL_main.
ENDCLASS.
START-OF-SELECTION.
DATA: main1 TYPE REF TO CL_main.
DATA: eventhandler1 TYPE REF TO CL_eventhandler.
CREATE OBJECT main1.
CREATE OBJECT eventhandler1.
SET HANDLER eventhandler1->handling_CUTOFF FOR main1.
main1->PRO( 4 ).
CLASS CL_main IMPLEMENTATION.
METHOD PRO.
num1 = num2.
IF num2 >= 2.
RAISE EVENT CUTOFF.
ENDIF. ENDMETHOD.
ENDCLASS.
CLASS CL_eventhandler IMPLEMENTATION.
METHOD handling_CUTOFF.
WRITE: 'Handling the CutOff'.
WRITE: / 'Event has been processed'.
ENDMETHOD.
ENDCLASS.

The above code produces the following output:

Handling the CutOff Event has been processed

Interfaces



             Similar to classes in ABAP, interfaces act as data types for objects. The components of interfaces are same as the components of classes. Unlike the declaration of classes, the declaration of an interface does not include the visibility sections. This is because the components defined in the declaration of an interface are always integrated in the public visibility section of the classes.
Interfaces are used when two similar classes have a method with the same name, but the functionalities are different from each other. Interfaces might appear similar to classes, but the functions defined in an interface are implemented in a class to extend the scope of that class. Interfaces along with the inheritance feature provide a base for polymorphism. This is because a method defined in an interface can behave differently in different classes.

Following is the general format to create an interface:

INTERFACE <intf_name>.
DATA.....
CLASS-DATA.....
METHODS.....
CLASS-METHODS.....
ENDINTERFACE.

       In this syntax, <intf_name> represents the name of an interface. The DATA and CLASS-DATA statements can be used to define the instance and static attributes of the interface respectively. The METHODS and CLASS-METHODS statements can be used to define the instance and static methods of the interface respectively. As the definition of an interface does not include the implementation class, it is not necessary to add the DEFINITION clause in the declaration of an interface.

Note: All the methods of an interface are abstract. They are fully declared including their parameter interface, but not implemented in the interface. All the classes that want to use an interface must implement all the methods of the interface. Otherwise, the class becomes an abstract class.

We use the following syntax in the implementation part of the class:

INTERFACES <intf_name>.

In this syntax, <intf_name> represents the name of an interface. Note that this syntax must be used in the public section of the class.

The following syntax is used to implement the methods of an interface inside the implementation of a class:

METHOD <intf_name~method_m>.
<statements>.
ENDMETHOD.

In this syntax, <intf_name~method_m> represents the fully declared name of a method of the <intf_name> interface.

Example


Report ZINTERFACE1.
INTERFACE my_interface1.
Methods msg.
ENDINTERFACE.
CLASS num_counter Definition.
PUBLIC Section.
INTERFACES my_interface1.
Methods add_number.
PRIVATE Section.
Data num Type I.
ENDCLASS.
CLASS num_counter Implementation.
Method my_interface1~msg.
Write: / 'The number is', num.
EndMethod.
Method add_number.
ADD 7 TO num.
EndMethod.
ENDCLASS.
CLASS drive1 Definition.
PUBLIC Section.
INTERFACES my_interface1.
Methods speed1.
PRIVATE Section.
Data wheel1 Type I.
ENDCLASS.
CLASS drive1 Implementation.
Method my_interface1~msg.
Write: / 'Total number of wheels is', wheel1.
EndMethod.
Method speed1.
Add 4 To wheel1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data object1 Type Ref To num_counter.
Create Object object1.
CALL Method object1->add_number.
CALL Method object1->my_interface1~msg.
Data object2 Type Ref To drive1.
Create Object object2.
CALL Method object2->speed1.
CALL Method object2->my_interface1~msg.

The above code produces the following output:

The number is 7
Total number of wheels is 4

In the above example, my_interface1 is the name of an interface that contains the 'msg' method. Next, two classes, num_counter and drive1 are defined and implemented. Both these classes implement the 'msg' method and also specific methods that define the behavior of their respective instances, such as the add_number and speed1 methods.

Note: The add_number and speed1 methods are specific to the respective classes.


ABAP – Encapsulation



      Encapsulation is an Object Oriented Programming (OOP) concept that binds together data and functions that manipulate the data, and keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Encapsulation is a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

ABAP supports the properties of encapsulation and data hiding through the creation of user-defined types called classes. As discussed earlier, a class can contain private, protected and public members. By default, all items defined in a class are private.

Encapsulation by Interface


Encapsulation actually means one attribute and method could be modified in different classes. Hence data and method can have different form and logic that can be hidden to separate class.

Let's consider encapsulation by interface. Interface is used when we need to create one method with different functionality in different classes. Here the name of the method need not be changed. The same method will have to be implemented in different class implementations.

Example


The following program contains an Interface inter_1. We have declared attribute and a method method1. We have also defined two classes like Class1 and Class2. So we have to implement the method ‘method1’ in both of the class implementations. We have implemented the method ‘method1’ differently in different classes. In the start-of-selection, we create two objects Object1 and Object2 for two classes. Then, we call the method by different objects to get the function declared in separate classes.

Report ZEncap1.
Interface inter_1.
Data text1 Type char35.
Methods method1.
EndInterface.
CLASS Class1 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class2 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class1 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 1 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
CLASS Class2 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 2 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: Object1 Type Ref To Class1, Object2 Type Ref To Class2.
Create Object: Object1, Object2.
CALL Method: Object1->inter_1~method1, Object2->inter_1~method1.

The above code produces the following output:

Class 1 Interface method
Class 2 Interface method

Encapsulated classes do not have a lot of dependencies on the outside world. Moreover, the interactions that they do have with external clients are controlled through a stabilized public interface. That is, an encapsulated class and its clients are loosely coupled. For the most part, classes with well-defined interfaces can be plugged into another context. When designed correctly, encapsulated classes become reusable software assets.

Designing Strategy


Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That is just good encapsulation. This wisdom is applied most frequently to data members and it also applies equally to all members.

ABAP – Polymorphism



        The term polymorphism literally means ‘many forms’. From an object-oriented perspective, polymorphism works in conjunction with inheritance to make it possible for various types within an inheritance tree to be used interchangeably. That is, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

      ABAP polymorphism means that a call to a method will cause a different method to be executed depending on the type of object that invokes the method.

The following program contains an abstract class 'class_prgm', 2 sub classes (class_procedural and class_OO), and a test driver class 'class_type_approach'. In this implementation, the class method 'start' allow us to display the type of programming and its approach. If you look closely at the signature of method 'start', you will observe that it receives an importing parameter of type class_prgm. However, in the Start-Of-Selection event, this method has been called at run-time with objects of type class_procedural and class_OO.

Example


Report ZPolymorphism1.
CLASS class_prgm Definition Abstract.
PUBLIC Section.
Methods: prgm_type Abstract, approach1 Abstract.
ENDCLASS.
CLASS class_procedural Definition Inheriting From class_prgm.
PUBLIC Section.
Methods: prgm_type Redefinition, approach1 Redefinition.
ENDCLASS.
CLASS class_procedural Implementation.
Method prgm_type.
Write: 'Procedural programming'.
EndMethod.
Method approach1.
Write: 'top-down approach'.
EndMethod.
ENDCLASS.
CLASS class_OO Definition Inheriting From class_prgm.
PUBLIC Section.
Methods: prgm_type Redefinition, approach1 Redefinition.
ENDCLASS.
CLASS class_OO Implementation.
Method prgm_type.
Write: 'Object oriented programming'.
EndMethod.
Method approach1.
Write: 'bottom-up approach'.
EndMethod.
ENDCLASS.
CLASS class_type_approach Definition.
PUBLIC Section.
CLASS-METHODS: start Importing class1_prgm Type Ref To class_prgm.
ENDCLASS.
CLASS class_type_approach IMPLEMENTATION.
Method start.
CALL Method class1_prgm->prgm_type.
Write: 'follows'.
CALL Method class1_prgm->approach1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: class_1 Type Ref To class_procedural, class_2 Type Ref To class_OO.
Create Object class_1.
Create Object class_2.
CALL Method class_type_approach=>start Exporting class1_prgm = class_1.
New-Line.
CALL Method class_type_approach=>start Exporting class1_prgm = class_2.

The above code produces the following output:

Procedural programming follows top-down approach
Object oriented programming follows bottom-up approach

ABAP run-time environment performs an implicit narrowing cast during the assignment of the importing parameter class1_prgm. This feature helps the 'start' method to be implemented generically. The dynamic type information associated with an object reference variable allows the ABAP run-time environment to dynamically bind a method call with the implementation defined in the object pointed to by the object reference variable. For instance, the importing parameter 'class1_prgm' for method 'start' in the 'class_type_approach' class refers to an abstract type that could never be instantiated on its own.

Whenever the method is called with a concrete sub class implementation such as class_procedural or class_OO, the dynamic type of the class1_prgm reference parameter is bound to one of these concrete types. Therefore, the calls to methods 'prgm_type' and 'approach1' refer to the implementations provided in the class_procedural or class_OO sub classes rather than the undefined abstract implementations provided in class 'class_prgm'.



ABAP – Inheritance



          One of the most important concepts in object oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.

When creating a class, instead of writing completely new data members and methods, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or super class, and the new class is referred to as the derived class or sub class.

 An object of one class can acquire the properties of another class.
 Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods.
 The main advantage of inheritance is reusability.

The inheritance relationship is specified using the ‘INHERITING FROM’ addition to
the class definition statement.

Following is the syntax: CLASS <subclass> DEFINITION INHERITING FROM <superclass>.

Example


Report ZINHERITAN_1.
 CLASS Parent Definition.
PUBLIC Section. Data: w_public(25) Value 'This is public data'.
Methods: ParentM.
ENDCLASS.
CLASS Child Definition Inheriting From Parent.
PUBLIC Section.
Methods: ChildM.
ENDCLASS.
CLASS Parent Implementation.
Method ParentM.
Write /: w_public.
EndMethod.
ENDCLASS.
CLASS Child Implementation.
Method ChildM.
Skip.
Write /: 'Method in child class', w_public.
EndMethod.
ENDCLASS.
Start-of-selection.
Data:
Parent Type Ref To Parent,
Child Type Ref To Child.
Create Object: Parent, Child.
Call Method:
Parent->ParentM,
child->ChildM.

The above code produces the following output:

This is public data
Method in child class
This is public data

Access Control and Inheritance


A derived class can access all the non-private members of its base class. Thus super class members that should not be accessible to the member functions of sub classes should be declared private in the super class. We can summarize the different access types according to who can access them in the following way:



When deriving a class from a super class, it can be inherited through public, protected or private inheritance. The type of inheritance is specified by the access specifier as explained above. We hardly use protected or private inheritance, but public inheritance is commonly used. The following rules are applied while using different types of inheritance.

 Public Inheritance: When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class.

 Protected Inheritance: When deriving from a protected super class, public and protected members of the super class become protected members of the sub class.

 Private Inheritance: When deriving from a private super class, public and protected members of the super class become private members of the sub class.

Example


Report Zinheri_Redefine.
CLASS super_class Definition.
Public Section.
Methods: Addition1 importing g_a TYPE I g_b TYPE I exporting g_c TYPE I.
ENDCLASS.
CLASS super_class Implementation.
Method Addition1. g_c = g_a + g_b.
EndMethod.
ENDCLASS.
CLASS sub_class Definition Inheriting From super_class.
Public Section.
METHODS: Addition1 Redefinition.
ENDCLASS.
CLASS sub_class Implementation.
Method Addition1.
g_c = g_a + g_b + 10.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Parameters: P_a Type I, P_b TYPE I.
Data: H_Addition1 TYPE I.
Data: H_Sub TYPE I.
Data: Ref1 TYPE Ref TO sub_class.
Create Object Ref1.
Call Method Ref1->Addition1 exporting g_a = P_a g_b = P_b Importing g_c = H_Addition1.
Write:/ H_Addition1.

After executing F8, if we enter the values 9 and 10, the above code produces the following output:


Redefinition Demo
29




Friday 24 November 2017

ABAP – Classes


A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

Class Definition and Implementation


When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, what an object of the class will consist of, and what operations can be performed on such an object. That is, it defines the abstract characteristics of an object, such as attributes, fields, and properties.

The following syntax shows how to define a class:

CLASS <class_name> DEFINITION.
..........
..........
ENDCLASS.

A class definition starts with the keyword CLASS followed by the class name, DEFINITION and the class body. The definition of a class can contain various components of the class such as attributes, methods, and events. When we declare a method in the class declaration, the method implementation must be included in the class implementation. The following syntax shows how to implement a class:
CLASS <class_name> IMPLEMENTATION.
...........
..........
ENDCLASS.

Note: Implementation of a class contains the implementation of all its methods. In ABAP Objects, the structure of a class contains components such as attributes, methods, events, types, and constants.

Attributes


Attributes are data fields of a class that can have any data type such as C, I, F, and N. They are declared in the class declaration. These attributes can be divided into 2 categories: instance and static attributes. An instance attribute defines the instance specific state of an object. The states are different for different objects. An instance attribute is declared by using the DATA statement.

Static attributes define a common state of a class that is shared by all the instances of the class. That is, if you change a static attribute in one object of a class, the change is visible to all other objects of the class as well. A static attribute is declared by using the CLASS-DATA statement.

Methods


A method is a function or procedure that represents the behavior of an object in the class. The methods of the class can access any attribute of the class. The definition of a method can also contain parameters, so that you can supply the values to these parameters when methods are called. The definition of a method is declared in the class declaration and implemented in the implementation part of a class. The METHOD and ENDMETHOD statements are used to define the implementation part of a method. The following syntax shows how to implement a method:

METHOD <m_name>.
..........
..........
ENDMETHOD.

In this syntax, <m_name> represents the name of a method. Note: You can call a method by using the CALL METHOD statement.

Accessing Attributes and Methods


Class components can be defined in public, private, or protected visibility sections that control how these components could be accessed. The private visibility section is used to deny access to components from outside of the class. Such components can only be accessed from inside the class such as a method.

Components defined in the public visibility section can be accessed from any context. By default all the members of a class would be private. Practically, we define data in private section and related methods in public section so that they can be called from outside of the class as shown in the following program.

 The attributes and methods declared in Public section in a class can be accessed by that class and any other class, sub-class of the program.

 When the attributes and methods are declared in Protected section in a class, those can be accessed by that class and sub classes (derived classes) only.

 When the attributes and methods are declared in Private section in a class, those can be accessed by only that class and not by any other class.

Example


Report ZAccess1.
CLASS class1 Definition.
PUBLIC Section.
Data: text1 Type char25 Value 'Public Data'.
Methods meth1.
PROTECTED Section.
Data: text2 Type char25 Value 'Protected Data'.
PRIVATE Section.
Data: text3 Type char25 Value 'Private Data'.
ENDCLASS.
CLASS class1 Implementation.
Method meth1.
Write: / 'Public Method:', / text1, / text2, / text3.
Skip.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: Objectx Type Ref To class1.
Create Object: Objectx.
CALL Method: Objectx->meth1.
Write: / Objectx->text1.

The above code produces the following output:

Public Method:
Public Data
Protected Data
Private Data
Public Data

Static Attributes


A Static attribute is declared with the statement CLASS-DATA. All the objects or instances can use the static attribute of the class. Static attributes are accessed directly with the help of class name like class_name=>name_1 = 'Some Text'.

Example


Following is a program where we want to print a text with line number 4 to 8 times. We define a class class1 and in the public section we declare CLASS-DATA (static attribute) and a method. After implementing the class and method, we directly access the static attribute in Start-Of-Selection event. Then we just create the instance of the class and call the method.

Report ZStatic1.
CLASS class1 Definition.
PUBLIC Section.
CLASS-DATA: name1 Type char45, data1 Type I.
Methods: meth1.
ENDCLASS.
CLASS class1 Implementation.
Method meth1.
Do 4 Times. data1 = 1 + data1.
Write: / data1, name1. EndDo.
Skip.
EndMethod.
ENDCLASS.
Start-Of-Selection.
class1=>name1 = 'ABAP Object Oriented Programming'.
class1=>data1 = 0.
Data: Object1 Type Ref To class1, Object2 Type Ref To class1.
Create Object: Object1, Object2.
CALL Method: Object1->meth1, Object2->meth1.

The above code produces the following output:





Constructors


Constructors are special methods that are called automatically, either while creating an object or accessing the components of a class. Constructor gets triggered whenever an object is created, but we need to call a method to trigger the general method. In the following example, we have declared two public methods method1 and constructor. Boththese methods have different operations. While creating an object of the class, the constructor method triggers its operation.

Example


Report ZConstructor1.
CLASS class1 Definition.
PUBLIC Section.
Methods: method1, constructor.
ENDCLASS.
CLASS class1 Implementation.
Method method1.
Write: / 'This is Method1'.
EndMethod.
Method constructor.
Write: / 'Constructor Triggered'.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data Object1 Type Ref To class1.
Create Object Object1.

The above code produces the following output:

Constructor Triggered

ME Operator in Methods


When you declare a variable of any type in public section of a class, you can use it in any other implementation. A variable can be declared with an initial value in public section. We may declare the variable again inside a method with a different value. When we write the variable inside the method, the system will print the changed value. To reflect the previous value of the variable, we have to use ‘ME’ operator.

In this program, we have declared a public variable text1 and initiated with a value. We have declared the same variable again, but instantiated with different value. Inside the method, we are writing that variable with ‘ME’ operator to get the previously initiated value. We get the changed value by declaring directly.

Example


Report ZMEOperator1.
CLASS class1 Definition.
PUBLIC Section.
Data text1 Type char25 Value 'This is CLASS Attribute'.
Methods method1.
ENDCLASS.
CLASS class1 Implementation.
Method method1.
Data text1 Type char25 Value 'This is METHOD Attribute'.
Write: / ME->text1, / text1.
ENDMethod.
ENDCLASS.
Start-Of-Selection.
Data objectx Type Ref To class1.
Create Object objectx.
CALL Method objectx->method1.

The above code produces the following output:

This is CLASS Attribute
This is METHOD Attribute

ABAP – Objects



An object is a special kind of variable that has distinct characteristics and behaviors. The characteristics or attributes of an object are used to describe the state of an object, and behaviors or methods represent the actions performed by an object.

An object is a pattern or instance of a class. It represents a real-world entity such as a person or a programming entity like variables and constants. For example, accounts and students are examples of real-world entities. But hardware and software components of a computer are examples of programming entities.

An object has the following three main characteristics:

 Has a state.
 Has a unique identity.
 May or may not display the behavior.

The state of an object can be described as a set of attributes and their values. For example, a bank account has a set of attributes such as Account Number, Name, Account Type, Balance, and values of all these attributes. The behavior of an object refers to the changes that occur in its attributes over a period of time.

Each object has a unique identity that can be used to distinguish it from other objects. Two objects may exhibit the same behavior and they may or may not have the same state, but they never have the same identity. Two persons may have the same name, age, and gender but they are not identical. Similarly, the identity of an object will never change throughout its lifetime.

Objects can interact with one another by sending messages. Objects contain data and code to manipulate the data. An object can also be used as a user-defined data type with the help of a class. Objects are also called variables of the type class. After defining a class, you can create any number of objects belonging to that class. Each object is associated with the data of the type class with which it has been created.


Creating an Object


The object creation usually includes the following steps:

 Creating a reference variable with reference to the class. The syntax for which is:

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

 Creating an object from the reference variable. The syntax for which is:

CREATE Object: <object_name>.

Example


REPORT ZDEMO_OBJECT.
CLASS Class1 Definition. Public Section.
DATA: text1(45) VALUE 'ABAP Objects.'.
METHODS: Display1.
ENDCLASS.
CLASS Class1 Implementation.
METHOD Display1.
Write:/ 'This is the Display method.'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA: Class1 TYPE REF TO Class1.
CREATE Object: Class1.
Write:/ Class1->text1.
CALL METHOD: Class1->Display1.

The above code produces the following output:

ABAP Objects.

This is the Display method.


ABAP – Object Orientation


         Object orientation simplifies software design to make it easier to understand, maintain, and reuse. Object Oriented Programming (OOP) represents a different way of thinking in writing software. The beauty of OOP lies in its simplicity. The expressiveness of OOP makes it easier to deliver quality software components on time.

As solutions are designed in terms of real-world objects, it becomes much easier for programmers and business analysts to exchange ideas and information about a design that uses a common domain language. These improvements in communication help to reveal hidden requirements, identify risks, and improve the quality of software being developed. The object-oriented approach focuses on objects that represent abstract or concrete things of the real world. These objects are defined by their character and properties that are represented by their internal structure and their attributes (data). The behavior of these objects is described by methods (i.e. functionality).

Let’s compare the procedural and object oriented programming:

       ABAP was initially developed as a procedural language (just similar to earlier procedural programming language like COBOL). But ABAP has now adapted the principles of object oriented paradigms with the introduction of ABAP Objects. The object-oriented concepts in ABAP such as class, object, inheritance, and polymorphism, are essentially the same as those of other modern object-oriented languages such as Java or C++.

As object orientation begins to take shape, each class assumes specific role assignments. This division of labor helps to simplify the overall programming model, allowing each class to specialize in solving a particular piece of the problem at hand. Such classes have high cohesion and the operations of each class are closely related in some intuitive way.

The key features of object orientation are:

 Effective programming structure.
 Real-world entities can be modeled very well.
 Stress on data security and access.
 Minimizes code redundancy.
 Data abstraction and encapsulation.

ABAP – Deleting Internal Tables


          The DELETE statement is used to delete one or more records from an internal table. The records of an internal table are deleted either by specifying a table key or condition or by finding duplicate entries. If an internal table has a non-unique key and contains duplicate entries, the first entry from the table is deleted.

Following is the syntax to use the DELETE statement to delete a record or line from an internal table:
DELETE TABLE <internal_table> FROM <work_area_itab>.

In the above syntax, the <work_area_itab> expression is a work area and it should be compatible with the type of the <internal_table> internal table. The delete operation is performed on the basis of a default key that could be taken from the work area components.

You may also specify a table key explicitly in the DELETE TABLE statement by using the following syntax:

DELETE TABLE <internal_table> WITH TABLE KEY <K1> = <F1>…………
<Kn> = <Fn>.

In this syntax, <F1>, <F2>....<Fn> are the fields of an internal table and <K1>, <K2>....<Kn> are the key fields of the table. The DELETE statement is used to delete the records or lines of the <internal_table> table based on the expressions <K1> = <F1>, <K2> = <F2>...<Kn> = <Fn>.
Note: If the data types of the <F1>, <F2>....<Fn> fields are not compatible with the <K1>, <K2>...<Kn> key fields then the SAP system automatically converts them into the compatible format.

Example


REPORT ZDELETE_DEMO.

DATA: BEGIN OF Line1,
ColP TYPE I,
ColQ TYPE I,
END OF Line1.
DATA mytable LIKE HASHED TABLE OF Line1 WITH UNIQUE KEY ColP.
DO 8 TIMES.
Line1-ColP = SY-INDEX.
Line1-ColQ = SY-INDEX + 4.
INSERT Line1 INTO TABLE mytable.
ENDDO.
Line1-ColP = 1.
DELETE TABLE mytable: FROM Line1,
WITH TABLE KEY ColP = 3.
LOOP AT mytable INTO Line1.
WRITE: / Line1-ColP, Line1-ColQ.
ENDLOOP.

The above code produces the following output:

2     6
4     8
5     9
6    10
7    11
8    12

In this example, mytable has two fields, ColP and ColQ. Initially, mytable is populated with eight lines, where the ColP contains the values 1, 2, 3, 4, 5, 6, 7 and 8. The ColQ contains the values 5, 6, 7, 8, 9, 10, 11 and 12 because the ColP values are incremented by 4 every time.

The DELETE statement is used to delete the lines from mytable where the value of the ColP key field is either 1 or 3. After deletion, the ColP field of mytable contains the values 2, 4, 5, 6, 7 and 8, as shown in the output. The ColQ field contains the values 6, 8, 9, 10, 11 and 12.

ABAP – Reading Internal Tables


  We can read the lines of a table by using the following syntax of the READ TABLE statement:
READ TABLE <internal_table> FROM <work_area_itab>.

   In this syntax, the <work_area_itab> expression represents a work area that is compatible with the line type of the <internal_table> table. We can specify a search key, but not a table key, within the READ statement by using the WITH KEY clause, as shown in the following syntax:

READ TABLE <internal_table> WITH KEY = <internal_tab_field>.

Here the entire line of the internal table is used as a search key. The content of the entire line of the table is compared with the content of the <internal_tab_field> field. If the values of the <internal_tab_field> field are not compatible with the line type of the table, these values are converted according to the line type of the table. The search key allows you to find entries in internal tables that do not have a structured line type, that is, where the line is a single field or an internal table type.

The following syntax of the READ statement is used to specify a work area or field symbol by using the COMPARING clause:

READ TABLE <internal_table> <key> INTO <work_area_itab> [COMPARING <F1> <F2>...<Fn>].

When the COMPARING clause is used, the specified table fields <F1>, <F2>....<Fn> of the structured line type are compared with the corresponding fields of the work area before being transported. If the ALL FIELDS clause is specified, the SAP system compares all the components. When the SAP system finds an entry on the basis of a key, the value of the SY-SUBRC variable is set to 0. In addition, the value of the SY-SUBRC variable is set to 2 or 4 if the content of the compared fields is not the same or if the SAP system cannot find an entry. However, the SAP system copies the entry into the target work area whenever it finds an entry, regardless of the result of the comparison.


Example


REPORT ZREAD_DEMO.
*/Creating an internal table DATA: BEGIN OF Record1,
ColP TYPE I,
ColQ TYPE I,
END OF Record1.
DATA mytable LIKE HASHED TABLE OF Record1 WITH UNIQUE KEY ColP.
DO 6 Times.
Record1-ColP = SY-INDEX.
Record1-ColQ = SY-INDEX + 5.
INSERT Record1 INTO TABLE mytable. ENDDO.
Record1-ColP = 4.
Record1-ColQ = 12.
READ TABLE mytable FROM Record1 INTO Record1 COMPARING ColQ.
WRITE: 'SY-SUBRC =', SY-SUBRC.
SKIP.
WRITE: / Record1-ColP, Record1-ColQ.

The above code produces the following output:

SY-SUBRC =     2

              4                      9

In the above example, mytable is an internal table of the hashed table type, with Record1 as the work area and ColP as the unique key. Initially, mytable is populated with six lines, where the ColP field contains the values of the SY-INDEX variable and the ColQ field contains (SY-INDEX + 5) values.

The Record1 work area is populated with 4 and 12 as values for the ColP and ColQ fields respectively. The READ statement reads the line of the table after comparing the value of the ColP key field with the value in the Record1 work area by using the COMPARING clause, and then copies the content of the read line in the work area. The value of the SY-SUBRC variable is displayed as 2 because when the value in the ColP field is 4, the value in the ColQ is not 12, but 9.


ABAP – Copying Internal Tables


          When we read a record from an internal table with a header line, that record is moved from the table itself into the header line. It is then the header line that our program works with. The same applies while creating a new record. It is the header line with which you work with and from which the new record is sent to the table body itself.

To copy the records, we can use a SELECT statement to select all of the records from the table and then use MOVE statement that will move the records from the original table into the new internal table into the fields where the names correspond.

Following is the syntax for MOVE statement:

MOVE <table_field> TO <internal_tab_field>.

Example


REPORT ZCUSLIST1.
TABLES: ZCUSTOMERS1.
DATA: BEGIN OF itab01 Occurs 0,
name LIKE ZCUSTOMERS1-name,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.
Select * FROM ZCUSTOMERS1.
MOVE ZCUSTOMERS1-name TO itab01-name.
MOVE ZCUSTOMERS1-dob TO itab01-dob. ENDSELECT.
Write: / itab01-name, itab01-dob.

The above code produces the following output:

MARGARET       02.11.1994

The select loop fills each field one at a time, using the MOVE statement to move the data from one table’s field to the other. In the above example, MOVE statements were used to move the contents of the ZCUSTOMERS1 table to the corresponding fields in the internal table. You can accomplish this action with just one line of code. You can use the MOVE-CORRESPONDING statement. Following is the syntax for MOVE-CORRESPONDING statement:

MOVE-CORRESPONDING <table_name> TO <internal_tab>.

It tells the system to move the data from the fields of ZCUSTOMERS1 to their corresponding fields in itab01.


Example


REPORT ZCUSTOMERLIST. 
TABLES: ZCUSTOMERS1.
DATA: Begin of itab01 occurs 0,
customer LIKE ZCUSTOMERS1-customer,
name LIKE ZCUSTOMERS1-name,
title LIKE ZCUSTOMERS1-title,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.
SELECT * from ZCUSTOMERS1.
MOVE-Corresponding ZCUSTOMERS1 TO itab01.
APPEND itab01.
ENDSELECT.
LOOP AT itab01.
Write: / itab01-name, itab01-dob.
ENDLOOP.

The above code produces the following output:
 MARK                    21.05.1981
 JAMES                   14.08.1977
 AURIELE               19.06.1990
 STEPHEN               22.07.1985
 MARGARET          02.11.1994

This is made possible by the fact that both have matching field names. When making use of this statement, you need to make sure that both fields have matching data types and lengths. It has been done here with the LIKE statement previously.

ABAP – Populating Internal Tables


     In internal tables, populating includes features such as selection, insertion and append. This chapter focuses on INSERT and APPEND statements.

INSERT Statement


INSERT statement is used to insert a single line or a group of lines into an internal table.
Following is the syntax to add a single line to an internal table:

INSERT <work_area_itab> INTO <internal_tab> INDEX <index_num>.

In this syntax, the INSERT statement inserts a new line in the internal_tab internal table. A new line can be inserted by using the work_area_itab INTO expression before the internal_tab parameter. When the work_area_itab INTO expression is used, the new line is taken from the work_area_itab work area and inserted into the internal_tab table. However, when the work_area_itab INTO expression is not used to insert a line, the line is taken from the header line of the internal_tab table.
When a new line is inserted in an internal table by using the INDEX clause, the index number of the lines after the inserted line is incremented by 1. If an internal table contains <index_num> - 1 lines, the new line is added at the end of the table. When the SAP system successfully adds a line to an internal table, the SY-SUBRC variable is set to 0.


Example


Following is a sample program that uses the insert statement.

REPORT ZCUSLIST1.
DATA: BEGIN OF itable1 OCCURS 4, F1 LIKE SY-INDEX,
END OF itable1.
DO 4 TIMES.
itable1-F1 = sy-index.
APPEND itable1.
ENDDO.
itable1-F1 = -96.
INSERT itable1 INDEX 2.
LOOP AT itable1.
Write / itable1-F1.
ENDLOOP.
LOOP AT itable1 Where F1 >= 3.
itable1-F1 = -78.
INSERT itable1.
ENDLOOP.
Skip.
LOOP AT itable1.
Write / itable1-F1.
ENDLOOP.

The above code produces the following output:

                   1
96-
                   2

                   3
4




                  1

96-

                  2

78-

3

78-

4

In the above example, the DO loop appends 4 rows containing the numbers 1 through 4 to it. The header line component itable1-F1 has been assigned a value of -96. Insert statement inserts the header line as new row into the body before row 3. The existing row 3 becomes row 4 after the insert. The LOOP AT statement retrieves those rows from the internal table that have an F1 value greater than or equal to 3. Before each row, Insert statement inserts a new row from the header line of it. Prior to the insert, the F1 component has been changed to contain -78.

After each insert statement is executed, the system re-indexes all rows below the one inserted. This introduces overhead when you insert rows near the top of a large internal table. If you need to insert a block of rows into a large internal table, prepare another table with the rows to be inserted and use insert lines instead.

When inserting a new row inside itable1 inside of a loop at itable1, it doesn’t affect the internal table instantly. It actually becomes effective on the next loop pass. While inserting a row after the current row, the table is re-indexed at the ENDLOOP. The sy-tabix is incremented and the next loop processes the row pointed to by sy-tabix. For instance, if you are in the second loop pass and you insert a record before row 3. When endloop is executed, the new row becomes row 3 and the old row 3 becomes row 4 and so on. Sy-tabix is incremented by 1, and the next loop pass processes the newly inserted record.

APPEND Statement


The APPEND statement is used to add a single row or line to an existing internal table. This statement copies a single line from a work area and inserts it after the last existing line in an internal table. The work area can be either a header line or any other field string with the same structure as a line of an internal table. Following is the syntax of the APPEND statement that is used to append a single line in an internal table:

APPEND <record_for_itab> TO <internal_tab>.


In this syntax, the <record_for_itab> expression can be represented by the <work_area_itab> work area, which is convertible to a line type or by the INITIAL LINE clause. If the user uses a <work_area_itab> work area, the SAP system adds a new line to the <internal_tab> internal table and populates it with the content of the work area. The INITIAL LINE clause appends a blank line that contains the initial value for each field of the table structure. After each APPEND statement, the SY-TABIX variable contains the index number of the appended line.

Appending lines to standard and sorted tables with a non-unique key works regardless of whether the lines with the same key already exist in the table. In other words, duplicate entries may occur.

However, a run-time error occurs if the user attempts to add a duplicate entry to a sorted table with a unique key or if the user violates the sort order of a sorted table by appending the lines to it.

 Example


REPORT ZCUSLIST1.
DATA: BEGIN OF linv Occurs 0, Name(20) TYPE C, ID_Number TYPE I, END OF linv.
DATA table1 LIKE TABLE OF linv.
linv-Name = 'Melissa'.
linv-ID_Number = 105467.
APPEND linv TO table1.
LOOP AT table1 INTO linv.
Write: / linv-name, linv-ID_Number.
ENDLOOP.

The above code produces the following output:

Melissa        105467

ABAP – Creating Internal Tables


       DATA statement is used to declare an internal table. The program must be told where the table begins and ends. So use the BEGIN OF statement and then declare the table name. After this, the OCCURS addition is used, followed by a number, here 0. OCCURS tells SAP that an internal table is being created, and the 0 states that it will not contain any records initially. It will then expand as it is filled with data.

Following is the syntax:

DATA: BEGIN OF <internal_tab> Occurs 0,

Let’s create the fields on a new line. For instance, create ‘name’ which is declared as LIKE ZCUSTOMERS1-name. Create another field called ‘dob’, LIKE ZCUSTOMERS1-dob. It is useful initially to give the field names in internal tables the same names as other fields that have been created elsewhere. Finally, declare the end of the internal table with “END OF <internal_tab>.” as shown in the following code:

DATA: BEGIN OF itab01 Occurs 0,
name LIKE ZCUSTOMERS1-name,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.

Here ‘itab01’ is commonly used shorthand when creating temporary tables in SAP. The OCCURS clause is used to define the body of an internal table by declaring the fields for the table. When the OCCURS clause is used, you can specify a numeric constant ‘n’ to determine additional default memory if required. The default size of memory that is used by the OCCUR 0 clause is 8 KB. The structure of the internal table is now created, and the code can be written to fill it with records.

An internal table can be created with or without using a header line. To create an internal table with a header line, use either the BEGIN OF clause before the OCCURS clause or the WITH HEADER LINE clause after the OCCURS clause in the definition of the internal table. To create an internal table without a header line, use the OCCURS clause without the BEGIN OF clause.

You can also create an internal table as a local data type (a data type used only in the context of the current program) by using the TYPES statement. This statement uses the TYPE or LIKE clause to refer to an existing table.

The syntax to create an internal table as a local data type is:

TYPES <internal_tab> TYPE|LIKE <internal_tab_type> OF <line_type_itab> WITH <key> INITIAL SIZE <size_number>.

Here the <internal_tab_type> specifies a table type for an internal table <internal_tab> and <line_type_itab> specifies the type for a line of an internal table. In TYPES statement, you can use the TYPE clause to specify the line type of an internal table as a data type and LIKE clause to specify the line type as a data object. Specifying a key for an internal tableis optional and if the user does not specify a key, the SAP system defines a table type with an arbitrary key.

INITIAL SIZE <size_number> creates an internal table object by allocating an initial amount of memory to it. In the preceding syntax, the INITIAL SIZE clause reserves a memory space for size_number table lines. Whenever an internal table object is declared, the size of the table does not belong to the data type of the table.

Note: Much less memory is consumed when an internal table is populated for the first time.

Example


Step 1: Open the ABAP Editor by executing the SE38 transaction code. The initial screen of ABAP Editor appears.

Step 2: In the initial screen, enter a name for the program, select the Source code radio button and click the Create button to create a new program.

Step 3: In the 'ABAP: Program Attributes' dialog box, enter a short description for the program in the Title field, select the 'Executable program' option from the Type drop-down menu in the Attributes group box. Click the Save button.

Step 4: Write the following code in ABAP editor.

REPORT ZINTERNAL_DEMO.
TYPES: BEGIN OF CustomerLine,
Cust_ID TYPE C,
Cust_Name(20) TYPE C,
END OF CustomerLine.

TYPES mytable TYPE SORTED TABLE OF CustomerLine
WITH UNIQUE KEY Cust_ID.
 WRITE:/'The mytable is an Internal Table'.

Step 5: Save, activate and execute the program as usual.
In this example, mytable is an internal table and a unique key is defined on the Cust_ID field.

The above code produces the following output:

The mytable is an Internal Table.

ABAP – Internal Tables


Internal table is actually a temporary table, which contains the records of an ABAP program that it is being executed. An internal table exists only during the run-time of a SAP program. They are used to process large volumes of data by using ABAP language. We need to declare an internal table in an ABAP program when you need to retrieve data from database tables.

Data in an internal table is stored in rows and columns. Each row is called a line and each column is called a field. In an internal table, all the records have the same structure and key. The individual records of an internal table are accessed with an index or a key. As internal table exists till the associated program is being executed, the records of the internal table are discarded when the execution of the program is terminated. So internal tables can be used as temporary storage areas or temporary buffers where data can be modified as required. These tables occupy memory only at run-time and not at the time of their declaration.

Internal tables only exist when a program is running, so when the code is written, the internal table must be structured in such a way that the program can make use of it. You will find that internal tables operate in the same way as structures. The main difference being that structures only have one line, while an internal table can have as many lines as required.

An internal table can be made up of a number of fields, corresponding to the columns of a table, just as in the ABAP dictionary a table was created using a number of fields. Key fields can also be used with internal tables, and while creating these internal tables they offer slightly more flexibility. With internal tables, one can specify a non-unique key, allowing any number of non-unique records to be stored, and allowing duplicate records to be stored if required.

The size of an internal table or the number of lines it contains is not fixed. The size of an internal table changes according to the requirement of the program associated with the internal table. But it is recommended to keep internal tables as small as possible. This is to avoid the system running slowly as it struggles to process enormous amounts of data.

Internal tables are used for many purposes:

 They can be used to hold results of calculations that could be used later in the program.

 An internal table can also hold records and data so that this can be accessed quickly rather than having to access this data from database tables.

 They are hugely versatile. They can be defined using any number of other defined structures.

Example


Assume that a user wants to create a list of contact numbers of various customers from one or several large tables. The user first creates an internal table, selects the relevant data from customer tables and then places the data in the internal table. Other users can access and use this internal table directly to retrieve the desired information, instead of writing database queries to perform each operation during the run-time of the program.


Internal Table Basics

Internal table is a data object in ABAP that exists only at run time of a program. It means when the
program execution is complete then the internal table will be lost. We use internal table to store 
database table data after fetching it by a select query. The ABAP run-time system dynamically 
manages the internal table’s memory. It means we developer do not need to work on memory
 management of internal table.

Internal table has three parts – rows, columns & work area.
1.       Rows are the line type of internal table. It is a structure which contains several fields. 
Those fields are of data elements. We need to declare the structure locally or globally to 
declare the internal table.
2.       Columns are the fields of internal table. Those fields are of different data elements 
declared by locally or globally.
3.       The most important part of an internal table is its work area. Work area is basically
 the line type of an internal table. It means it has the same structure of the rows of internal table. 
Work area contains the same fields of same type of the rows. It is of two types – implicit & explicit 
work area.

    A.      When we declare an internal table with header line then a work area is automaticallycreated with the 
same name of the table. This work area is called implicit work area which is actually the header line.
 There is no need to declare work area separately.This work area / header line contains the same table 
 as of the internal table.


Example –

TYPESBEGIN OF ty_mat,

         matnr TYPE mara-matnr,
         werks TYPE marc-werks,
         lgort TYPE mard-lgort,
       END OF ty_mat.

DATA: it_mat TYPE STANDARD TABLE OF ty_mat WITH NON-UNIQUE KEY
      matnr WITH HEADER LINE.


Here we have declared a local structure ty_mat. This is the line type / row of the 
internal table. It means the table will contain rows which has three fields
 (matnr, werks & lgort). We declare the internal table it_mat with this local structure.
 We also can declare with global structure.


DATA: it_qinfo TYPE TABLE OF slis_qinfo_alv WITH HEADER LINE

      WITH NON-UNIQUE KEY type.

Here slis_qinfo_alv is a structure which has been declared globally in data dictionary. 
We can declare the internal table directly with the table type also.

DATA: it_qinfo TYPE slis_t_add_fieldcat WITH HEADER LINE.

Here slis_t_add_fieldcat is a table type declared in data dictionary.

Header line concept:

MATNR                 WERKS                 LGORT



 The name of this work area / header line is IT_MAT.

When we create the internal table then it is like following:

MATNR                 WERKS                LGORT















It also contains the same name IT_MAT but it is mentioned IT_MAT[ ] in the program.

B.      If we declare an internal table without header line then we need to declare its 
work area seperately. Since we are declaring the work area explicitly it is called explicit 
work area. This work area contains the different name from the internal table.

Example –

TYPESBEGIN OF ty_mat,

         matnr TYPE mara-matnr,
         werks TYPE marc-werks,
         lgort TYPE mard-lgort,
       END OF ty_mat.

DATA: it_mat TYPE STANDARD TABLE OF ty_mat,
      wa_mat TYPE ty_mat.

Similarly we can declare internal table with globally declared structure or table type also.
DATA: it_qinfo TYPE TABLE OF slis_qinfo_alv WITH NON-UNIQUE KEY type.
DATA: it_qinfo TYPE slis_t_qinfo_alv.

Work area concept:

MATNR                 WERKS                 LGORT



 The name of this work area is WA_MAT.

When we create the internal table then it is like following:

MATNR                 WERKS                LGORT















The table contains the name IT_MAT.

In today’s programming header line is not used in internal table. It is now obsolete. There are two main
 reasons for that.
1.       The automatically generated header line / implicit work area has the same name as of internal table. 
That’s why it loses the readability of program.
2.       When we use nested data objects (internal table has components of structure which is another
 internal table) then header line is not allowed. In object oriented programming header line is not allowed.

To declare an internal table there is three basic specifications. They are 1. Row type, 2. Key & 3. Types 
of internal table. Internal table is of three types – standard table, sorted table & hashed table. Standard 
& sorted tables are called index table because we can access its records by its index. Index is nothing
but a row number of the internal table.

1.       Standard table is an index table which has non-unique key. It can be accessed by index or key also.
If we want to access by key then the key must be defined otherwise default key would be considered. 
The declaration is as follows:

DATA: it_mat TYPE STANDARD TABLE OF ty_mat WITH NON-UNIQUE KEY matnr.
OR
DATA: it_mat TYPE TABLE OF ty_mat WITH NON-UNIQUE KEY matnr.

If we don’t mention “Standard table of” clause then by default the system takes it as a standard 
internal table. We can enter data into a standard internal table by using the APPEND statement. 
Append always enters data at the last row of the table.

APPEND wa_mat TO it_mat.

2.       Sorted table is another kind of index table which has unique / non unique key. It also can be 
accessed via index or key. For sorted table the key must be specified. The declaration is as follows:

DATA: it_mat TYPE SORTED TABLE OF ty_mat WITH UNIQUE KEY matnr,
      it_mat TYPE SORTED TABLE OF ty_mat WITH NON-UNIQUE KEY matnr.

Unique key means the MATNR (material no) will must be unique. If same material number is inserted
 then a run time error will happen. However we can declare the sorted table with non unique key also. 
In this case same material number can be entered but it will be sorted after entering the number. 
Here the sorted table behaves similar to sorted standard table. We use INSERT statement to enter
 any records to the sorted table.

INSERT wa_mat INTO it_mat.

3.       Hashed table is not an index table. It follows the hash algorithm. Here the declaration of key is 
must and also the key must be unique. Hence no duplicate entry will be in the hashed table. We can 
access records only by the key.

DATA: it_mat TYPE HASHED TABLE OF ty_mat WITH UNIQUE KEY matnr.

Similar to sorted tables data can be inserted here by INSERT statement. Hashed tables are used
 when the internal table contains huge volume of data.

INSERT wa_mat INTO TABLE it_mat.

Table kind
Index Tables
Hashed Tables
Standard Table
Sorted Table
Index Access
Yes
Yes
No
Key Access
Yes
Yes
Yes
Key Uniqueness
Non unique
Unique/Non unique
Unique
Usage
Index access
Key access
Only key access