ABAP OOPS Tutorials
ABAP OOPS Tutorials
2011
BANGALORE
Understanding the concepts of Object Oriented
Programming
What is Object Orientation?
In the past, information systems used to be defined primarily by their functionality: Data
and functions were kept separate and linked together by means of input and output
relations.
Objects: An object is a section of source code that contains data and provides
services. The data forms the attributes of the object. The services are known as
methods (also known as operations or functions). They form a capsule which
combines the character to the respective behavior. Objects should enable
programmers to map a real problem and its proposed software solution on a one-to-
one basis.
Classes: Classes describe objects. From a technical point of view, objects are
runtime instances of a class. In theory, you can create any number of objects based
on a single class. Each instance (object) of a class has a unique identity and its own
set of values for its attributes.
Global Class: Global classes and interfaces are defined in the Class Builder (Transaction
SE24) in the ABAP Workbench. They are stored centrally in class pools in the class library in
the R/3 Repository. All of the ABAP programs in an R/3 System can access the global
classes
Local Class: Local classes are define in an ABAP program (Transaction SE38) and can only
be used in the program in which they are defined.
Local Classes
Definition: This section is used to declare the components of the classes such as attributes,
methods, events .They are enclosed in the ABAP statements CLASS ... ENDCLASS.
Methods:- Block of code, providing some functionality offered by the class. Can
be compared to function modules. They can access all of the attributes of a class.
Methods are defined in the definition part of a class and implement it in the
implementation part using the following processing block:
METHOD <meth>.
...
ENDMETHOD.
Events:- A mechanism set within a class which can help a class to trigger
methods of other class.
Instance components exist separately in each instance (object) of the class and
Static components only exist once per class and are valid for all instances of the
class. They are declared with the CLASS- keywords
Static components can be used without even creating an instance of the class
and are referred to using static component selector „=>‟.
2. Visibility of Components
Each class component has a visibility. In ABAP Objects the whole class definition is
separated into three visibility sections: PUBLIC, PROTECTED, and PRIVATE.
Data declared in public section can be accessed by the class itself, by its
subclasses as well as by other users outside the class.
Data declared in the protected section can be accessed by the class itself, and
also by its subclasses but not by external users outside the class.
Data declared in the private section can be accessed by the class only, but not
by its subclasses and by external users outside the class.
The Grey block of code is for object creation. This object creation includes two steps:
Inheritance.
Abstraction.
Encapsulation.
Polymorphism
Inheritance is the concept of adopting the features from the parent and reusing them . It
involves passing the behavior of a class to another class. You can use an existing class to
derive a new class. Derived classes inherit the data and methods of the super class.
However, they can overwrite existing methods, and also add new ones.
more).
Multiple inheritance: Acquiring the properties from more than one parent.
Example
Tomato1
(Best color)
Tomato2
(Best Size)
Tomato3
(Best Taste)
Syntax : CLASS <subclass> DEFINITION INHERITING FROM <superclass>.
Let us see a very simple example for creating subclass(child) from a superclass(parent)
Multiple Inheritance is not supported by ABAP.
Output is as follows :
Abstraction: Everything is visualized in terms of classes and objects.
Encapsulation The wrapping up of data and methods into a single unit (called class) is
known as Encapsulation. The data is not accessible to the outside world only those methods,
which are wrapped in the class, can access it.
Steps involved:
"Extra Credit": If you have extra time, try any of the following:
Replace the SET_BALANCE method with a constructor. Pass the opening balance
when you instantiate the account object.
Create a static attribute and methods to set and get the name of the bank that
holds the accounts.
Place the mouse cursor in DEPOSIT and hit the Parameters button.
And WITHDRAW
For withdraw we define an exception.
We can see the attributes and methods by pressing “Display object list” button on top.
Now we are almost done creating the object. Press CTRL + F3 to activate or hit the
Matchstick.
Now we are done building the global class we can test it. Press F8.
Click SET_BALANCE. Write the NEW_BALANCE and press ENTER.
We get an exception.
Given below is an example code for using the global class we defined.
REPORT ZGB_OOPS_BANK .
start-of-selection.
REPORT Z_OOABAP19 .
CLASS lcl_company_employees DEFINITION.
PUBLIC SECTION.
TYPES:
BEGIN OF t_employee,
no TYPE i,
name TYPE string,
wage TYPE i,
END OF t_employee.
METHODS:
constructor,
add_employee
IMPORTING im_no TYPE i
im_name TYPE string
im_wage TYPE i,
display_employee_list,
display_no_of_employees.
PRIVATE SECTION.
CLASS-DATA: i_employee_list TYPE TABLE OF t_employee,
no_of_employees TYPE i.
ENDCLASS.
*-- CLASS LCL_CompanyEmployees IMPLEMENTATION
CLASS lcl_company_employees IMPLEMENTATION.
METHOD constructor.
no_of_employees = no_of_employees + 1.
ENDMETHOD.
METHOD add_employee.
* Adds a new employee to the list of employees
DATA: l_employee TYPE t_employee.
l_employee-no = im_no.
l_employee-name = im_name.
l_employee-wage = im_wage.
APPEND l_employee TO i_employee_list.
ENDMETHOD.
METHOD display_employee_list.
* Displays all employees and there wage
DATA: l_employee TYPE t_employee.
WRITE: / 'List of Employees'.
LOOP AT i_employee_list INTO l_employee.
WRITE: / l_employee-no, l_employee-name, l_employee-wage.
ENDLOOP.
ENDMETHOD.
METHOD display_no_of_employees.
* Displays total number of employees
SKIP 3.
WRITE: / 'Total number of employees:', no_of_employees.
ENDMETHOD.
ENDCLASS.
*******************************************************
* Sub class LCL_BlueCollar_Employee
*******************************************************
CLASS lcl_bluecollar_employee DEFINITION
INHERITING FROM lcl_company_employees.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING im_no TYPE i
im_name TYPE string
im_hours TYPE i
im_hourly_payment TYPE i,
add_employee REDEFINITION.
PRIVATE SECTION.
DATA:no TYPE i,
name TYPE string,
hours TYPE i,
hourly_payment TYPE i.
ENDCLASS.
* constructor method
CALL METHOD super->constructor.
no = im_no.
name = im_name.
hours = im_hours.
hourly_payment = im_hourly_payment.
ENDMETHOD.
METHOD add_employee.
* Calculate wage an call the superclass method add_employee to add
*******************************************************
*REPORT
*******************************************************
DATA:
* Object references
o_bluecollar_employee1 TYPE REF TO lcl_bluecollar_employee,
o_whitecollar_employee1 TYPE REF TO lcl_whitecollar_employee.
START-OF-SELECTION.
* Create bluecollar employee obeject
CREATE OBJECT o_bluecollar_employee1
EXPORTING im_no = 1
im_name = 'Vikram.C'
im_hours = 38
im_hourly_payment = 75.
* Add bluecollar employee to employee list
CALL METHOD o_bluecollar_employee1->add_employee
EXPORTING im_no = 1
im_name = 'Vikram.C'
im_wage = 0.
* Create whitecollar employee obeject
CREATE OBJECT o_whitecollar_employee1
EXPORTING im_no = 2
im_name = 'Raghava.V'
im_monthly_salary = 10000
im_monthly_deducations = 2500.
* Add bluecollar employee to employee list
CALL METHOD o_whitecollar_employee1->add_employee
EXPORTING im_no = 1
im_name = 'Vikram.C'
im_wage = 0.
* Display employee list and number of employees. Note that the result
* will be the same when called from o_whitecollar_employee1 or
* o_bluecolarcollar_employee1, because the methods are defined
* as static (CLASS-METHODS)
CALL METHOD o_whitecollar_employee1->display_employee_list.
CALL METHOD o_whitecollar_employee1->display_no_of_employees.
Demo program illustrating Interface
*&---------------------------------------------------------------------*
*& Report Z_OOABAP20 *
*& *
*&---------------------------------------------------------------------*
*& *
*& *
*&---------------------------------------------------------------------*
REPORT Z_OOABAP20
.
INTERFACE lif_employee.
METHODS:
add_employee
IMPORTING im_no TYPE i
im_name TYPE string
im_wage TYPE i.
ENDINTERFACE.
*******************************************************
* Super class LCL_CompanyEmployees
*******************************************************
display_employee_list,
display_no_of_employees.
PRIVATE SECTION.
CLASS-DATA: i_employee_list TYPE TABLE OF t_employee,
no_of_employees TYPE i.
ENDCLASS.
*******************************************************
* Sub class LCL_BlueCollar_Employee
*******************************************************
ENDCLASS.
*******************************************************
* Sub class LCL_WhiteCollar_Employee
*******************************************************
CLASS lcl_whitecollar_employee DEFINITION
*******************************************************
*REPORT
*******************************************************
DATA:
* Object references
o_bluecollar_employee1 TYPE REF TO lcl_bluecollar_employee,
o_whitecollar_employee1 TYPE REF TO lcl_whitecollar_employee.
START-OF-SELECTION.
* Create bluecollar employee obeject
CREATE OBJECT o_bluecollar_employee1
EXPORTING im_no = 1
im_name = 'Chandrasekhar'
im_hours = 38
im_hourly_payment = 75.
* Add bluecollar employee to employee list
CALL METHOD o_bluecollar_employee1->lif_employee~add_employee
EXPORTING im_no = 1
im_name = 'Vikram C'
im_wage = 0.
* Create whitecollar employee obeject
CREATE OBJECT o_whitecollar_employee1
EXPORTING im_no = 2
im_name = 'Raghava V'
im_monthly_salary = 10000
im_monthly_deducations = 2500.
* Add bluecollar employee to employee list
CALL METHOD o_whitecollar_employee1->lif_employee~add_employee
EXPORTING im_no = 1
im_name = 'Gylle Karen'
im_wage = 0.
* Display employee list and number of employees. Note that the result
* will be the same when called from o_whitecollar_employee1 or
* o_bluecolarcollar_employee1, because the methods are defined
* as static (CLASS-METHODS)
CALL METHOD o_whitecollar_employee1->display_employee_list.
CALL METHOD o_whitecollar_employee1->display_no_of_employees.
Global Class Functionality (Step-by-step approach)
Go to SE24 T-Code.
Provide method.
Goto Attributes
Go to methods tab.
And double click on the method select method.
Go back
Execute it.
Working with the Keyword SUPER in object
Oriented Programming
SUPER is the key word used to represent the super class of a class in oops you can access
the methods and attributes of the super class using this word SUPER.
Press CREATE.
Save it.
Provide parameter for this method.
Go to SE24.
In this we can provide super class name in the sub class attributes.
Save it.
Go to attributes tab.
Save it.
Go to the methods.
Then go to SE38.
*&---------------------------------------------------------------------*
*& Report ZCL_SUB_METHOD *
*& *
*&---------------------------------------------------------------------*
*& How to work with SUPER keyword
*
*& *
*&---------------------------------------------------------------------*
REPORT ZCL_SUB_METHOD .
*Provide object for sub class
DATA: OBJ TYPE REF TO ZCL_SUB_METHOD.
*provide parameters
PARAMETERS: P_VBELN TYPE VBAK-VBELN.
*Provide data object
DATA: WA_VBAK TYPE VBAK,
WA_VBAP TYPE VBAP,
IT_VBAP TYPE Z_VBAP.
*Create the object
CREATE OBJECT OBJ.
*Call select method
CALL METHOD OBJ->SELECT_METHOD
EXPORTING
P_VBELN = P_VBELN
IMPORTING
WA_VBAK = WA_VBAK.
*Display header data
WRITE:/ WA_VBAK-VBELN,
WA_VBAK-ERDAT,
WA_VBAK-ERZET,
WA_VBAK-ERNAM.
SKIP 2.
*Provide item data
IT_VBAP = OBJ->IT_VBAP."For Your Reference this IT_VBAP is declared in attribute
*Display item data
LOOP AT IT_VBAP INTO WA_VBAP.
WRITE:/ WA_VBAP-VBELN,
WA_VBAP-POSNR,
WA_VBAP-MATKL.
ENDLOOP.
Here one important point is by using one object in the sub class.
Execute it.
Working with Inheritance
Inheritance is the concept of passing the behavior of a class to another class.
Inheritance:
Inheritance is the process by which object of one class acquire the properties of
another class.
Advantage of this property is reusability.
This means we can add additional features to an existing class with out modifying it.
Go to SE38.
Save it.
Save it.
*&---------------------------------------------------------------------*
*& Report ZLOCALCLASS_VARIABLES *
*& *
*&---------------------------------------------------------------------*
*& How to work Constructor *
*& VikramChellappa *
*&---------------------------------------------------------------------*
REPORT ZLOCALCLASS_VARIABLES.
*OOPS CONSTRUCTOR.
**PROVIDE DATA TYPES "CONSTRUCTOR DOES NOT HAVE ANY EXPORT PARAMETERS.
*DATA: C TYPE I.
*DEFINE THE CLASS.
CLASS CL_LC DEFINITION.
PUBLIC SECTION.
METHODS: CONSTRUCTOR IMPORTING A TYPE I,
* EXPORTING B TYPE I, "IT TAKES ONLY IMPORT PARAMETERS
ANOTHER.
ENDCLASS.
*class implementation.
CLASS CL_LC IMPLEMENTATION.
METHOD CONSTRUCTOR.
WRITE:/ 'THIS IS CONSTRUCTOR METHOD'.
WRITE:/ 'A =', A.
ENDMETHOD.
METHOD ANOTHER.
WRITE:/ 'THIS IS ANOTHER METHOD' COLOR 5.
ENDMETHOD.
ENDCLASS.
*create the object.
DATA OBJ TYPE REF TO CL_LC.
START-OF-SELECTION.
CREATE OBJECT OBJ EXPORTING A = 10.
* IMPORTING B = C.
*call the method.
SKIP 2.
CALL METHOD OBJ->ANOTHER.
Execute it.
Go back to methods. And provide the logic by double click on the method name.
Then save it, check it, activate it and execute it.
Press F8.
Now we will create a program using the above class for inserting the data into the database
table.
*&---------------------------------------------------------------------*
*& Report ZPG_INSERTINTODB *
*& *
*&---------------------------------------------------------------------*
*& *
*& *
*&---------------------------------------------------------------------*
REPORT ZPG_INSERTINTODB.
*provide the object for the class
DATA: OBJ_INSERT TYPE REF TO ZCL_INSERTDB.
*provide parameters
PARAMETERS: V_VBELN TYPE VBELN,
V_ERDAT TYPE ERDAT,
V_ERZET TYPE ERZET.
*provide work area
DATA: WA TYPE VBAK.
*create the object
START-OF-SELECTION.
CREATE OBJECT OBJ_INSERT.
*provide insert method
CALL METHOD OBJ_INSERT->INSERT_DATA
*provide exporting parameters
EXPORTING
P_VBELN = V_VBELN
P_ERDAT = V_ERDAT
P_ERZET = V_ERZET
*provide import parameters
IMPORTING
WA_VBAK = WA.
*display the data.
WRITE:/ WA-VBELN,
WA-ERDAT,
WA-ERZET.
Provide values.
Execute it.
Following is the sample output of the same:
Working with import, export and change
parameters of a class
Go to SE38 and create a program.
REPORT ZLOCALCLASS_VARIABLES.
*How we can use import and export and changing parameters in the class.
*Provide the variables
DATA: V_IMP TYPE I,
V_CHA TYPE I VALUE 100.
*Define the class.
CLASS CL_LC DEFINITION.
PUBLIC SECTION.
METHODS: DISPLAY IMPORTING A TYPE I
EXPORTING B TYPE I
CHANGING C TYPE I.
ENDCLASS.
*Implement the class.
CLASS CL_LC IMPLEMENTATION.
METHOD DISPLAY.
B = A + 20.
C = A + 30.
ENDMETHOD.
ENDCLASS.
*Create the object.
DATA OBJ TYPE REF TO CL_LC.
START-OF-SELECTION.
CREATE OBJECT OBJ.
CALL METHOD OBJ->DISPLAY
EXPORTING
A = 10
IMPORTING
B = V_IMP
CHANGING
C = V_CHA.
WRITE:/ 'OUTPUT PARAMETR', V_IMP,
'CHANGING PARAMETER', V_CHA.
Press F5.
Then
Final output.
Working on Polymorphism
POLYMORPHISM:-
Go to SE24 T-code.
Provide methods.
Select the first method then provide the parameters for this method.
Provide SUBCLASS:
Go to attribute provide the values that means provide super class name.
Go to Attributes.
Output :-
Click on continue.
Enter the New method “GET_DATA_NEW”
Click on Parameters.
Click on Pattern.
Click on continue.
Paste the Below Code.
*&---------------------------------------------------------------------*
*& Report ZENHANCE_TEST
*& DEMO FOR ENHANCING THE STANDARD CLASS.
REPORT ZENHANCE_TEST.
* TYPE DECLARATIONS
DATA : TABLE TYPE STRING,
ROW_COUNT TYPE I,
DATA_OUT TYPE TABLE OF SFLIGHT,
W_OUT LIKE LINE OF DATA_OUT.
* Calling the Enhanced class and Enhanced methods.
CALL METHOD CL_WDR_FLIGHTS=>GET_DATA_NEW
EXPORTING
* ROW_COUNT =
TAB_NAME = 'SFLIGHT'
CHANGING
DATA = DATA_OUT.
LOOP AT DATA_OUT INTO W_OUT.
WRITE :/ W_OUT-CARRID, W_OUT-FLDATE.
ENDLOOP.
We can use ABAP classes in the definition and runtime components of SAP Web Flow
Engine in the same way as object types defined in the Business object Repository (BOR).
Before proceeding further we need to know where to create and maintain ABAP Classes
and ABAP Interfaces.
The Class Builder allows us to create and maintain global ABAP classes and interfaces.
Both of these object types, like global data types, are defined in the ABAP Repository,
thus composing a central class library. Together, they form a central class library and are
visible throughout the system. We can display existing classes and interfaces in the class
library using the Class Browser.
We can define local classes as well as global classes. They are defined locally in programs,
function groups or as auxiliary classes of global classes of the class pools. Local classes are
only visible within the defining module.
To reach the initial screen of the Class Builder, choose Development Class Builder from
the initial screen of the ABAP Workbench or enter transaction code SE24.
4. How does it integrate?
The Class Builder allows us to create Web development objects within the ABAP Workbench.
We can use the Class Browser to display and maintain existing global object types from the
class library.
The diagram below illustrates the architecture of the Class Builder and the relationships
between its components (including the Class Browser)
From here, we can either display the contents of the class library or edit a class using the
Class Editor. Once we have defined an object type, we can implement its methods. From the
initial screen or the Class Editor, we can also access the Class Builder‟s test environment.
We can define the object types immediately after implementing the method in the ABAP
Editor. It is also possible to access the test environment from the initial screen or Class
Editor.
Display an overview (in the Class Browser) of global object types and their
relationships.
Maintain existing global classes or interfaces.
Create new global classes and interfaces.
Implement inheritance between global classes.
Create compound interfaces.
Create and specify the attributes, methods, and events of global classes and
interfaces.
Define internal types in classes.
Implement methods.
Redefine methods.
Maintain local auxiliary classes.
Test classes or interfaces in a simulated runtime environment.
Global classes and interfaces that we create in the Class Builder are stored in the class
library and administered by the R/3 Repository: they therefore have the same namespace
as all other Repository objects. It is therefore necessary to have naming conventions for
object types and their components and to use them uniformly within program
development.
The following naming convention has been conceived for use within the SAP namespace. If
we do not observe the naming conventions for object types (classes and interfaces),
conflicts will occur when the system creates persistent classes, since it will be unable to
generate the necessary co-classes.
For parameters:
RESULT RE_<result>
Within the SAP WebFlow Engine we can use ABAP classes that support the IF_WORKFLOW
interface. Classes that have implemented the IF_WORKFLOW interface are recognized as
workflow-enabled in the Class Builder.
The key attributes are used to define the object key. There can also be other defined
attributes other than key attributes. The SAP Web Flow Engine can access all public
attributes of a class.
Key Attributes:
In the Class Builder there is an additional column Key Attributes on the tab
page as shown below:
We need to check this box when we are defining any attribute as the Key Attribute.
All key fields must be character-type fields (elementary types: CHAR, NUMC) and have a
defined length. The maximum length allowed for all key fields is 32 characters. The length
of the key field for the persistent display is 32 characters.
In the case of persistent ABAP objects we can use the GUID, which is generated
automatically by the object manager when an instance is created.
Attributes:
In addition to all the other data types that the Class Builder supports, we can also define
attributes with reference to an object from the Business Object Repository (BOR). To do
this, we have to use the structure SWOTOBJID as the data type. The BOR object is
determined using the corresponding value.
To assign a BOR object instance to an attribute we need to use the corresponding BOR
macros. Normally, this is implemented within the CONSTRUCTOR of a class.
The IF_WORKFLOW interface is necessary when using an ABAP class within the SAP Web
Flow Engine. The interface contains methods that allow the object to be used within the SAP
Web Flow Engine.
The SAP Web Flow Engine handles all objects generically. Objects have to be saved in the
event of a context change. Therefore, it is necessary to convert object references in such a
way that they can be saved persistently. Conversely, we have to be able to generate the
corresponding instance of an ABAP class from the persistently saved key.
There are also a number of SAP Web Flow Engine components, for example, the Workflow
Log that can display objects. In this case the object has to provide corresponding functions.
The IF_WORKFLOW interface puts a logical parenthesis round the BI_PERSISTENT (instance
management) and BI_OBJECT (object behavior) interfaces. The IF_WORKFLOW interface
contains the following methods:
BI_PERSISTENT~FIND_BY_LPOR
BI_PERSISTENT~LPOR
BI_PERSISTENT~REFRESH
BI_OBJECT~DEFAULT_ATTRIBUTE_VALUE
BI_OBJECT~EXECUTE_DEFAULT_METHOD
BI_OBJECT~RELEASE
A class that implements the IF_WORKFLOW interface can be used in any workflow. The
class is automatically released for use in workflows when the interface is implemented.
Therefore, we can only make compatible changes to a class after implementation (we
cannot delete attributes, change types or delete methods). There is no where-used list to
show which workflows the class is used in.
Internal classes of an application should not implement the IF_WORKFLOW interface, since
this could mean that each method of the class is used in the workflow. Therefore, we should
encapsulate the workflow functions in another class that calls the selected methods of the
internal class.
Each method of the IF_WORKFLOW Interface as mentioned earlier has its distinct
functionality, which is discussed below.
Features:
The method parameter LPOR is the persistent object reference and is of SIBFLPOR structure
type. A reference of BI_PERSISTENT type is returned.
Field Description
CATID Describes the object type ( CL for ABAP classes)
TYPEID ABAP class name
INSTID Object key. The key is limited to 32 characters.
We can implement this method in several ways. In the case of persistent classes we can
create the ABAP object instance using the generated classes. In the case of individual
persistence management we have to implement the individual actions (such as creating an
instance, performing an existence check, entering public attributes, and so on) manually
within the class.
Instance management takes place automatically in the case of persistent classes. In the
case of individual persistence management we also have to carry out instance management
by class. The SAP Web Flow Engine does not provide any instance management. We must
therefore implement our own instance management in the case of individual persistence
management.
The FIND_BY_LPOR method should always return the same instance if the following
problems are to be avoided:
Inconsistency in the data display
Instance data being overwritten by another instance
Locking conflicts
There is an implementation example in the CL_SWF_FORMABSENC demo class.
17. BI_PERSISTENT~LPOR Method:
Features:
The method returns the persistent display of an object reference as a SIBFLPOR type
structure as described earlier.
There are also several ways of implementing this method in this case. There is an
implementation example in the CL_SWF_FORMABSENC demo class.
SAP Web Flow Engine calls the BI_PERSISTENT~REFRESH method when the system has to
ensure that all values of an object are valid or that they agree exactly with the persistent
display of the object.
Features:
The method implementation depends on the internal organization of the class. We can check
the object instance data in the database, if necessary.
If we do not need the method in our class, then we need only to carry out a “dummy”
implementation (without further coding) to avoid program errors when the system calls the
method.
Features:
We can display references to process objects or process step objects at different positions
within the SAP Web Flow Engine (for example, in Business Workplace and in Workflow Log).
The object key is normally displayed here. If, for example, we want to display a descriptive
text instead, the BI_OBJECT~DEFAULT_ATTRIBUTE_VALUE method has to return the
corresponding value.
If the method does not contain implementation or does not return a value, the object key is
displayed.
If we do not need the method in our class, then we need only to carry out a “dummy”
implementation (without further coding) to avoid program errors when the system calls the
method.
Features:
We can display process objects or process step objects at different positions within the SAP
Web Flow Engine (for example, in Business Workplace and in Workflow Log). The SAP Web
Flow Engine calls the BI_OBJECT~EXECUTE_DEFAULT_METHOD method.
If we do not need the method in our class, then we need only to carry out a “dummy”
implementation (without further coding) to avoid program errors when the system calls the
method.
The system indicates that the reference to the instance is no longer needed by using the
BI_OBJECT~RELEASE method. This means we can delete the reference from instance
management. Once the last reference has been deleted from instance management, the
GARBAGE COLLECTOR can release the corresponding memory area.
Features:
If we do not need the method in our class, then we need only to carry out a “dummy”
implementation (without further coding) to avoid program errors when the system calls the
method.
In process steps we can use methods and attributes of ABAP classes in the same way as
methods and attributes of Business Object Repository (BOR) objects. We can call these
methods in the process context.
Features:
While using the ABAP Classes in the Process Steps the methods may contain dialogs, they
can be synchronous or asynchronous; they may appear in the workflow log, and so on.
In general, we can use any method that is implemented as a public method. The method
can be implemented in the class itself, in one of the super classes of the class, or by way of
an interface.
The maximum permitted length for methods that are implemented by way of an interface,
for example IF_WORKFLOW~FIND_BY_LPOR, is 30 characters. If the method name is too
long, we can choose a shorter name for the method by defining an alias. If the method is
implemented in the class or in a super class, the name of the method cannot be longer than
30 characters, so this limitation does not apply.
Parameters:
We can assign values from the workflow container to the method parameters. Conversely,
export parameters can be entered as workflow container values. The following overview
shows how the individual types can be used as parameters:
TYPE SIBFLPORB
BOR objects
TYPE SIBFLPORB
TYPE SWOTOBJID
Object is transferred using the persistent display; this display is only valid for
BOR objects
TYPE SWC_OBJECT
Exceptions:
The SAP Web Flow Engine can deal with exceptions that are triggered by the methods. It
differentiates between application exceptions and temporary exceptions. The two exception
categories are differentiated by the exception in the class hierarchy or by naming
conventions. In the case of a temporary exception, the SAP Web Flow Engine attempts to
execute the method again. In the case of a permanent error the status for the workflow is
set to error.
Class-Based Exceptions:
To create a temporary exception, we can use, for example, the CX_BO_TEMPORARY class or
a corresponding subclass. It can be helpful to trigger an exception for dialog methods when
the user cancels the dialog. Here, for example, we could trigger the
CX_BO_ACTION_CANCELED exception (subclass of the CX_BO_TEMPORARY class).
We can also trigger exceptions not based on class. The SAP Web Flow Engine can
differentiate between the two exception categories (temporary and permanent) by the
name. If the exception begins with TMP or TEMP, it is a temporary exception; otherwise it is
a permanent exception.
Working with events in a Global Class
“I would like to explain about Working with Events in Global Class” .
Save it.
Go to event tab.
Save it.
Then provide link between method and also the event method.
METHOD METHOD_EVENT .
MESSAGE I000(0) WITH 'enter the values between 1000 and 2000'.
ENDIF.
SELECT *
FROM LFA1
INTO TABLE IT_LFA1
IT_LFA11 = IT_LFA1.
ENDMETHOD.
REPORT ZCL_EVENT_OPERATION .
START-OF-SELECTION.
EXPORTING
S_LIFNR_LOW = S_LIFNR-LOW
S_LIFNR_HIGH = S_LIFNR-HIGH
IT_LFA1 = IT_LFA1.
WRITE:/ WA_LFA1-LIFNR,
WA_LFA1-LAND1,
WA_LFA1-NAME1,
WA_LFA1-ORT01.
ENDLOOP.
Interfaces are listed in the definition part of the class, and must always be in the
PUBLIC SECTION.
Operations defined in the interface are implemented as methods of the class. All
methods of the interface must be present in the implementation part of the class.
Attributes, events, constants and types defined in the interface are automatically
available to the class carrying out the implementation.
Interface components are addressed in the class by <interface name>~<component
name>
Provide description.
Save it.
Save it.
Create it.
Save it.
Go to interface tab.
Save it.
Then we can see the interface method name in the class method.
Then double click on the method then write the logic here.
Then save it, check it, activate it.
*&---------------------------------------------------*
*& Report ZCL_INTERFACE *
*&---------------------------------------------------*
REPORT ZCL_INTERFACE .
*provide mara table
DATA: MARA TYPE MARA.
*provide data objects
DATA: OBJ TYPE REF TO ZCL_INTERFACE,
IT_MARA TYPE Z_MARA,
WA_MARA TYPE MARA.
*provide selection screen
SELECT-OPTIONS: S_MATNR FOR MARA-MATNR.
*provide object
START-OF-SELECTION.
CREATE OBJECT OBJ.
*call the method.
CALL METHOD OBJ->ZIF_INTERFACE~SELECT_METHOD
EXPORTING
P_MATNR_LOW = S_MATNR-LOW
P_MATNR_HIGH = S_MATNR-HIGH
IMPORTING
IT_MARA = IT_MARA
WA_MARA = WA_MARA.
*display the data
LOOP AT IT_MARA INTO WA_MARA.
WRITE:/ WA_MARA-MATNR,
WA_MARA-ERSDA,
WA_MARA-ERNAM,
WA_MARA-MATKL,
WA_MARA-MEINS.
ENDLOOP.
Then save it, check it ,activate it then execute it the output is like this.
ALIASES:
Go to se24.
Then go to SE38.
*&---------------------------------------------------------------------*
*& Report ZCL_INTERFACE *
*& *
*&---------------------------------------------------------------------*
REPORT ZCL_INTERFACE .
*provide mara table
DATA: MARA TYPE MARA.
*provide data objects
DATA: OBJ TYPE REF TO ZCL_INTERFACE,
IT_MARA TYPE Z_MARA,
WA_MARA TYPE MARA.
*provide selection screen
SELECT-OPTIONS: S_MATNR FOR MARA-MATNR.
*provide object
START-OF-SELECTION.
CREATE OBJECT OBJ.
*call the method.
* CALL METHOD OBJ->ZIF_INTERFACE~SELECT_METHOD
CALL METHOD OBJ->SEL
EXPORTING
P_MATNR_LOW = S_MATNR-LOW
P_MATNR_HIGH = S_MATNR-HIGH
IMPORTING
IT_MARA = IT_MARA
WA_MARA = WA_MARA.
*display the data
LOOP AT IT_MARA INTO WA_MARA.
WRITE:/ WA_MARA-MATNR,
WA_MARA-ERSDA,
WA_MARA-ERNAM,
WA_MARA-MATKL,
WA_MARA-MEINS.
ENDLOOP.
REPORT zclass_test.
*---------------------------------------------------------*
* CLASS zcl_test DEFINITION
*---------------------------------------------------------*
*
*---------------------------------------------------------*
CLASS zcl_test DEFINITION.
PUBLIC SECTION.
METHODS: display.
ENDCLASS. "zcl_test DEFINITION
*--------------------------------------------------------*
* CLASS zcl_test IMPLEMENTATION
*--------------------------------------------------------*
*
*--------------------------------------------------------*
CLASS zcl_test IMPLEMENTATION.
METHOD display.
WRITE: 'SAPTechnical.com'.
ENDMETHOD. "display
ENDCLASS. "zcl_test IMPLEMENTATION
Now let us create a global class SE24 using the above local class:
Go to transaction SE24.
Following pop-up appears:
Enter your Z program in which the local class is defined and press ENTER.
The class name defined in our program is ZCL_TEST and the proposed global class name is
CL_ZCL_TEST. Now you can rename the global class name as per your requirement.
If the local class is defined inside an include, we need to check the checkbox “Explode
INCLUDEs‟.
In the next screen give a description and choose the proper radio button
In the next screen provide report name (where the local class is defined), local class name
and method name.
Now save the
transaction and execute it.
In this case it will display the report.
This technique can be used to call a method (local class) from another program using
statement: call transaction.
Note: In the same way you can create a transaction on method of a global class.
Persistent Objects: A Quick Reference
Objective
To store references to the persistent object persistently in the database.
This table should contain 2 fields of type OS_GUID in addition to the GUID object attribute.
The first field is used to store the instance GUID while the other is used to store the class
GUID.
In the next screen select the class type as Persistent Class and then hit Save Button.
Step: 3 -> Persistent Mapping or Mapping
Goto->Persistence Representation
Give the table name. For e.g. ZSTUDENT03 and hit the enter button
Table fields appear in the lower half of the tool screen. Double Click the table field and press
the button. Add the remaining fields.
While adding the field INST_GUID choose the assignment type as Object reference and for
the attribute type specify the class name for e.g. ZCL_PERSIST_03
To assign a class indicator, select the corresponding table field of type OS_GUID by double-
clicking. Enter the name of the reference attribute for the attribute name.
Activate the Class. Press the Yes Button to activate the class actor as well.
TRY.
CALL METHOD AGENT->IF_OS_CA_PERSISTENCY~GET_PERSISTENT_BY_OID
EXPORTING
I_OID = '30EA9E25999F0843BE6F7B86063F2916'
RECEIVING
RESULT = REF1
.
CATCH CX_OS_OBJECT_NOT_FOUND .
CATCH CX_OS_CLASS_NOT_FOUND .
ENDTRY.
STUDENT ?= REF1.
STUDENT->SET_INST_GUID( STUDENT ).
COMMIT WORK.
Give persistent class name for e.g. ZCL_PERSIST_01 and hit the create button
In the next screen select the class type as Persistent Class and then hit Save Button.
Step: 2 -> Persistent Mapping or Mapping
Utilities->Persistence Representation
Give the table name. For e.g. ZSTUDENT01 and hit the enter button
Add the remaining fields as well. Screen looks like this now.
Activate the Class. Press the Yes Button to activate the class actor as well.
Step: 3 -> Write a Program to create / fetch / delete the Persistent Object
Here I am creating a new student. Specify the value and hit the execute button.
Output:
Go to SE16 and check the entries
Source Code
*&---------------------------------------------------------------------*
*& Report Z_GET_PERSISTENT
*& Published @ SAPTechnical.com
*&---------------------------------------------------------------------*
*&Author : Abdul Hakim
*&Development Language: ABAP
*&System Release: SAP Netweaver 2004
*&Title: Persistent Object using Business Key Object Identity!!
*&---------------------------------------------------------------------*
REPORT Z_GET_PERSISTENT.
selection-screen begin of block blk1 with frame title tit1.
parameters: sno like zstudent01-sno obligatory,
sname like zstudent01-sname obligatory,
mark1 like zstudent01-mark1 obligatory,
mark2 like zstudent01-mark2 obligatory.
selection-screen end of block blk1.
selection-screen begin of block blk2 with frame title tit2.
parameters: r1 type c radiobutton group rad1,
r2 type c radiobutton group rad1,
r3 type c radiobutton group rad1.
selection-screen end of block blk2.
*---------------------------------------------------------------------*
* CLASS lcl_class1 DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
class lcl_class1 definition.
public section.
data: agent type ref to zca_persist_01,
students type ref to zcl_persist_01.
data result1 type ref to zcl_persist_01.
methods: fetch_persistent importing im_sno like sno
im_sname like sname,
create_persistent importing im_sno like sno
im_sname like sname
im_mark1 like mark1
im_mark2 like mark2,
delete_persistent importing im_sno like sno
im_sname like sname,
output.
private section.
data: sno type zstudent01-sno,
sname type zstudent01-sname,
mark1 type zstudent01-mark1,
mark2 type zstudent01-mark2.
endclass. "lcl_class1 DEFINITION
*---------------------------------------------------------------------*
* CLASS lcl_class1 IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
class lcl_class1 implementation.
method fetch_persistent.
agent = zca_persist_01=>agent.
try.
agent->get_persistent( exporting i_sno = im_sno
i_sname = im_sname
receiving result = students ).
.
sname = students->get_sname( ).
sno = students->get_sno( ).
mark1 = students->get_mark1( ).
mark2 = students->get_mark2( ).
if r1 eq 'X'.
output( ).
endif.
CATCH CX_OS_OBJECT_NOT_FOUND .
MESSAGE 'Object doesn''t exists' TYPE 'I' DISPLAY LIKE 'E'.
endtry.
endmethod. "fetch_persistent
method output.
write:/ sno,
sname,
mark1,
mark2.
endmethod. "output
method create_persistent.
fetch_persistent( exporting im_sname = im_sname
im_sno = im_sno ).
try.
agent->create_persistent( exporting i_mark1 = im_mark1
i_mark2 = im_mark2
i_sname = im_sname
i_sno = im_sno
receiving result = students ).
commit work.
write 'Object Created'.
CATCH CX_OS_OBJECT_EXISTING .
MESSAGE 'Object already exists' TYPE 'I' DISPLAY LIKE 'E'.
endtry.
endmethod. "create_persistent
method delete_persistent.
fetch_persistent( exporting im_sname = im_sname
im_sno = im_sno ).
try.
agent->delete_persistent( exporting i_sname = im_sname
i_sno = im_sno ).
commit work.
write 'Object Deleted'.
CATCH CX_OS_OBJECT_NOT_EXISTING .
MESSAGE 'Object doesn''t exists' TYPE 'I' DISPLAY LIKE 'E'.
endtry.
endmethod. "delete_persistent
endclass. "lcl_class1 IMPLEMENTATION
data ref_class1 type ref to lcl_class1.
*---------------------------------------------------------------------*
* Load-of-Program
*---------------------------------------------------------------------*
load-of-program.
tit1 = text-001.
tit2 = text-001.
*---------------------------------------------------------------------*
* Start-of-Selection
*---------------------------------------------------------------------*
start-of-selection.
create object ref_class1.
if r1 eq 'X'.
ref_class1->fetch_persistent( exporting im_sno = sno
im_sname = sname ).
elseif r2 eq 'X'.
ref_class1->create_persistent( exporting im_sno = sno
im_sname = sname
im_mark1 = mark1
im_mark2 = mark2 ).
else.
ref_class1->delete_persistent( exporting im_sno = sno
im_sname = sname ).
endif.
Persistent Objects: Using GUID Object Identity
Objective
To Store the attributes of the Objects persistently in the database.
Every Persistent Object has a unique identity with which it can be accessed. There are 2
types of Object identity
1. Business Key
2. GUID( Global Unique Identifier )
For Persistent Objects using Business key Identity please check my previous article,
“Persistent Objects: Using Business Key identity”
Give persistent class name for eg ZCL_PERSIST_02 and hit the create button
In the next screen select the class type as Persistent Class and then hit Save Button.
Goto->Persistence Representation
Give the table name. For eg ZSTUDENT02 and hit the enter button
Activate the Class. Press the Yes Button to activate the class actor as well.
Unlike Business Key, GUID is not an attribute of the Persistent Class.
Step: 4 -> Write a Program to create / fetch / delete the Persistent Object
Our Program Selection-Screen looks like below
Here I am creating a new student. Specify the value and hit the execute button.
Output:
Source Code
*&-------------------------------------------------------------------*
*& Report Z_PERSISTENT_GUID
*&
*&-------------------------------------------------------------------*
*&Author : Abdul Hakim
*&Development Language: ABAP
*&System Release: SAP Netweaver 2004
*&Title: Persistent Object using GUID Object Identity!!
*&-------------------------------------------------------------------*
REPORT Z_PERSISTENT_GUID.
selection-screen begin of block b1 with frame title tit1.
parameters: sno like zstudent02-sno,
sname like zstudent02-sname,
mark1 like zstudent02-mark1,
mark2 like zstudent02-mark2,
guid like zstudent02-guid.
selection-screen end of block b1.
selection-screen begin of block b2 with frame title tit2.
parameters: r1 radiobutton group rad1,
r2 radiobutton group rad1,
r3 radiobutton group rad1.
selection-screen end of block b2.
data: agent type ref to zca_persist_02,
students type ref to zcl_persist_02.
data: result1 type ref to object,
result2 type ref to zcl_persist_02.
*-------------------------------------------------------------------*
* Load-of-Program
*-------------------------------------------------------------------*
load-of-program.
tit1 = text-001.
tit2 = tit1.
*-------------------------------------------------------------------*
* At Selection Screen
*-------------------------------------------------------------------*
at selection-screen.
if ( r2 eq 'X' ).
if sno is initial or sname is initial.
MESSAGE 'Enter the values in Sno/Sname fields'
TYPE 'E' DISPLAY LIKE 'E'.
endif.
endif.
*-------------------------------------------------------------------*
* Start-of-Selection
*-------------------------------------------------------------------*
start-of-selection.
agent = zca_persist_02=>agent.
if r1 eq 'X'.
TRY.
CALL METHOD AGENT->IF_OS_CA_PERSISTENCY~GET_PERSISTENT_BY_OID
EXPORTING
I_OID = guid
RECEIVING
RESULT = result1.
result2 ?= result1.
sno = result2->get_sno( ).
sname = result2->get_sname( ).
mark1 = result2->get_mark1( ).
mark2 = result2->get_mark2( ).
write:/ sno,
sname,
mark1,
mark2.
CATCH CX_OS_OBJECT_NOT_FOUND .
* CATCH CX_OS_CLASS_NOT_FOUND .
MESSAGE 'Object doesn''t exists' TYPE 'I' DISPLAY LIKE 'E'.
ENDTRY.
elseif r2 eq 'X'.
TRY.
CALL METHOD AGENT->CREATE_PERSISTENT
EXPORTING
I_MARK1 = mark1
I_MARK2 = mark2
I_SNAME = sname
I_SNO = sno
RECEIVING
RESULT = students.
commit work.
write 'Object Created'.
CATCH CX_OS_OBJECT_EXISTING .
MESSAGE 'Object already exists' TYPE 'I' DISPLAY LIKE 'E'.
ENDTRY.
else.
TRY.
CALL METHOD AGENT->IF_OS_CA_PERSISTENCY~GET_PERSISTENT_BY_OID
EXPORTING
I_OID = guid
RECEIVING
RESULT = result1.
CATCH CX_OS_OBJECT_NOT_FOUND .
* CATCH CX_OS_CLASS_NOT_FOUND .
MESSAGE 'Object doesn''t exists' TYPE 'I' DISPLAY LIKE 'E'.
ENDTRY.
result2 ?= result1.
TRY.
CALL METHOD AGENT->IF_OS_FACTORY~DELETE_PERSISTENT
EXPORTING
I_OBJECT = result2.
commit work.
write 'Object Deleted'.
CATCH CX_OS_OBJECT_NOT_EXISTING .
MESSAGE 'Object doesn''t exists' TYPE 'I' DISPLAY LIKE 'E'.
ENDTRY.
endif.
Implementing Persistent Service using Transaction
Service
Transaction Service is an object-oriented wrapper of SAP LUW.
In this article we will discuss how we can implement Persistent Service using Transaction
Service
Step: 1
Define methods.
Step: 2
Create OO transaction.
Go to Tcode SE93. Give Tcode name for eg Z_TX and hit the create button
Step: 6
Execute the transaction Z_TX
Step: 7
ABAP objects is the term given to object oriented programming done in ABAP. This
programming model unites data and functions. OO ABAP is built on existing ABAP language.
ABAP objects are run in same environment as the normal ABAP programs. OO ABAP is part
of ABAP since R/3 release 4.0
1.2 Class
Class is a prototype that defines data and the behaviour common to all the objects of
certain kind. Here methods provide the behaviour. We can say classes describe objects.
Classes can be declared either globally or locally. Global classes can be declared using
transaction SE24. Local classes are declared in an ABAP program (reports etc).
1.3 Objects
It signifies the real world. Technically we can say objects are instances of a class. We can
create any number of objects from a class template. All the objects created have unique
identity and each contain different set of attributes. Objects we create in a program exist
only till the program exists.
1.4 Encapsulation
Through encapsulation we restrict the visibility of attributes and methods in the object.
Public
Protected
Private
1.5 Polymorphism
The name of method is same but they behave differently in different classes. It means
implementation of method (i.e. body of the method) is different in different classes. It can
be achieved in two different ways in OO ABAP.
Interfaces
Overriding methods or redefining methods in each class after inheritance
1.6 Inheritance
In OO ABAP we use an existing class to derive a new class (child class). The new class
contains the attributes of the parent class (derives according to the visibility of attributes
and methods) in addition to new attributes and methods added to it. The child class derives
all the attributes and methods declared in parent class as public visibility. The child class
cannot inherit private members. The protected members in parent class are derived in child
class but their visibility changes to private.
1.7 Interfaces
Interfaces are similarly defined as classes. They also contain attributes and methods. But
interfaces do not have implementation part. Their methods are implemented in the class
that implements the interface.
It is the concept which determines the object‟s method to be invoked based on the
signature or parameters provided. It is important in case of invoking a method, which is
redefined in subsequent sub classes. As the level of hierarchy increases and the same
method is redefined in subclasses we need to know which method is called. When this
decision is made at run time it is called as Dynamic binding. When this decision is made at
compile time it is known as Static binding. In Java this concept is implemented using
concept of method overriding and in C++ there is concept of virtual functions. They help in
achieving dynamic binding. Similarly in OO ABAP we can redefine methods and use concept
of binding to invoke methods as per required.
Binding in OO ABAP
Suppose we need to redefine or override a method of a class in all sub classes inheriting
from it. We can take a pointer or reference variable to the base or parent class. This parent
class reference variable can take or refer to objects of the sub classes. Now to decide that
which method will be called upon while we are using this parent class reference variable, we
need to know about the concept of binding.
Now the reference variable obj_a no more refers to the object of <class name>.
In this case garbage collector will come and remove the object from memory.
2.1 Example
Let us create a report and some local classes and look into concept of binding
*&----------------------------------------------------------------*
*& Report ZPMM_CLASS_DYNAMIC *
*& *
*&----------------------------------------------------------------*
REPORT ZPMM_CLASS_DYNAMIC .
*----------------------------------------------------------------*
* CLASS a DEFINITION
*----------------------------------------------------------------*
CLASS a DEFINITION.
PUBLIC SECTION.
methods : rise,
fall.
ENDCLASS. "a DEFINITION
*----------------------------------------------------------------*
* CLASS a IMPLEMENTATION
*----------------------------------------------------------------*
CLASS a IMPLEMENTATION.
METHOD rise.
write : / 'Super class a --------- rise()'.
ENDMETHOD. "rise
METHOD fall.
write : / 'Super class a --------- fall()'.
ENDMETHOD. "fall
ENDCLASS. "a IMPLEMENTATION
*----------------------------------------------------------------*
* CLASS b DEFINITION
*----------------------------------------------------------------*
CLASS b DEFINITION inheriting from a.
PUBLIC SECTION.
methods : rise redefinition,
xyz.
ENDCLASS. "b DEFINITION
*----------------------------------------------------------------*
* CLASS b IMPLEMENTATION
*----------------------------------------------------------------*
CLASS b IMPLEMENTATION.
METHOD rise.
write : / 'Child class b redefined --------- rise()'.
ENDMETHOD. "rise
METHOD xyz.
write : / 'Child class b new method --------- xyz()'.
ENDMETHOD. "xyz
ENDCLASS. "b IMPLEMENTATION
********End of Class Definition and implementations***************
***Global declaration
***Creating reference variables for the classes defined above
data :
*Reference variable of type class a
obj_a type ref to a,
*Reference variable of type class b
obj_b1 type ref to b,
*Reference variable of type class b
obj_b2 type ref to b.
***********************************
******************************************************************
* START-OF-SELECTION
*******************************************************************
START-OF-SELECTION.
create object : obj_a,
obj_b1,
obj_b2.
******************************************************************
* END-OF-SELECTION
*******************************************************************
END-OF-SELECTION.
call method : obj_a->fall,
obj_a->rise,
obj_b1->fall.
We will just discuss how we got this output and what will happen when we assign subclass
objects to reference variables of parent class.
2.2 Binding
We have reference variables
Further we created object obj_a (refers to object of class a) and obj_b1(refers to object of
class b) using create object statement.
When we assign
obj_a = obj_b1.
Then both obj_a and obj_b now refer to same object of class b.
Now when
obj_a = obj_b .
When we will use the reference variable obj_a to invoke method rise() which is overridden
in sub class b, the sub class b method rise() (redefined method) is invoked.
*****************************************************************
* START-OF-SELECTION
******************************************************************
START-OF-SELECTION.
create object : obj_a,
obj_b1,
obj_b2.
obj_a = obj_b1.
*****************************************************************
* END-OF-SELECTION
******************************************************************
END-OF-SELECTION.
call method : obj_a->fall,
obj_a->rise,
obj_b1->fall.
Now output of above code is :
Super class a-----------fall()
Child class b redefined-----------rise()
Super class a-----------fall()
2.3 Binding Check Table
I have prepared a table to check the method invoked in case of inheritance. This table is
used to check the method invoked when the method is redefined in sub classes.
Note: We can not take a reference variable of Sub Class to refer a Base class object.
We can now verify the output of code given in section section 2.1.
In this case base class reference variable can only call the methods which are defined there
in the base class.
We can not invoke the new method defined in the class b xyz() using base class obj_a
reference variable.
obj_a = obj_b.
obj_a->rise.
When we call obj_a->fall , it will call the method of base class since it is not redefined in
sub class b.
When we call obj_a->rise, it will call the method of sub class since it is redefined in sub
class b. For this we can use the table of section 2.3.
We will just see the START-OF-SELECTION and END-OF-SELECTION events below from
section 2.1
******************************************************************
* START-OF-SELECTION
*******************************************************************
START-OF-SELECTION.
create object : obj_a,
obj_b1,
obj_b2.
******************************************************************
* END-OF-SELECTION
*******************************************************************
END-OF-SELECTION.
call method : obj_a->fall,
obj_a->rise,
obj_b1->fall.
Now output of above code is :
Super class a-----------fall()
Super class a-----------rise()
Super class a-----------fall()
Here obj_a refers to base class object so it only calls base class methods rise() and fall().
Since method fall() is not redefined in class b and is just inherited from class a , so when
we call obj_b1->fall, the base class method is invoked.
Understanding "ABAP Unit"
Introduction:
ABAP unit is based on ABAP objects. The global class CL_AUNIT_ASSERT contains methods
which can be used for testing .Tests are implemented in local classes. Inside the local class
the necessary method from the global class can be called for testing. These test classes can
be written inside the program for which the test is to be done. It will not affect our
production code in anyways.
Both the test class and test method should have FOR TESTING addition.
Ex:
PRIVATE SECTION.
ENDCLASS.
ASSERT_EQUALS
ASSERT_DIFFERS
ASSERT_BOUND
ASSERT_NOT_BOUND
ASSERT_INITIAL
ASSERT_NOT_INITIAL
ASSERT_CHAR_CP
ASSERT_CHAR_NP
ASSERT_EQUALS_F
FAIL
ABORT
ASSERT_NOT_INITIAL - checks whether the data object is not having its initial value.
ASSERT_EQUALS:
ASSERT_EQUALS is one of the methods in the class CL_AUNIT_ASSERT. This method can be
used for checking equality of two data objects.
(NO/METHOD/CLASS/PROGRAM)
Levels:
0 - Tolerable
1 - Critical
2 - Fatal
Quit:
Tolerance:
Ex:
Actual result – 24.
Tolerance – 0.9999.
Difference = Expected Result - Actual result.
= 1 > tolerance.
Therefore displays an error.
Example Program:
Let us consider an example for ABAP unit test using the method ASSERT_EQUALS to check
the equality of two data objects. In this program, we have two methods divide and factorial
in a local class MATH. We want to test the factorial method. So we have created one class
and one method MYTEST for testing. In the test method implementation we have called the
factorial method and so the data object RESULT is populated. Now we are going to compare
the actual data object (RESULT) with the expected result. For that we are calling the
ASSERT_EQUALS from the global class passing the expected result.
*----------------------------------------------------------------------*
* CLASS math DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS math DEFINITION.
PUBLIC SECTION.
METHODS divide
IMPORTING opr1 TYPE i
opr2 TYPE i
EXPORTING result TYPE f
RAISING cx_sy_arithmetic_error.
METHODS factorial
IMPORTING n TYPE i
RETURNING value(fact) TYPE i.
ENDCLASS. "math DEFINITION
*----------------------------------------------------------------------*
* CLASS math IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS math IMPLEMENTATION.
METHOD divide.
result = opr2 / opr1.
ENDMETHOD. "divide
METHOD factorial.
fact = 1.
IF n = 0.
RETURN.
ELSE.
DO n TIMES.
fact = fact * sy-index.
ENDDO.
ENDIF.
ENDMETHOD. "factorial
ENDCLASS. "math IMPLEMENTATION
START-OF-SELECTION.
DATA w_obj TYPE REF TO math.
DATA exc TYPE REF TO cx_sy_arithmetic_error.
DATA res TYPE f.
DATA result TYPE i.
DATA text TYPE string.
CREATE OBJECT w_obj.
TRY.
w_obj->divide( EXPORTING opr1 = 32 opr2 = 4
IMPORTING result = res ).
WRITE : res.
text = res.
CATCH cx_sy_arithmetic_error INTO exc.
text = exc->get_text( ).
MESSAGE text TYPE 'I'.
ENDTRY.
CREATE OBJECT w_obj.
COMPUTE result = w_obj->factorial( 4 ).
WRITE :/ 'The result for factorial is:',result.
*----------------------------------------------------------------------*
* CLASS mytest DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS mytest DEFINITION "#AU Risk_Level Harmless
FOR TESTING. "#AU Duration Short
PRIVATE SECTION.
METHODS mytest FOR TESTING.
ENDCLASS. "mytest DEFINITION
*----------------------------------------------------------------------*
* CLASS mytest IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS mytest IMPLEMENTATION.
METHOD mytest.
CREATE OBJECT w_obj.
result = w_obj->factorial( 4 ).
cl_aunit_assert=>assert_equals( act = result
exp = '24'
msg = 'Factorial Not calculated Correctly'
level = '0'
quit = '2'
tol = '0.999'
).
ENDMETHOD. "mytest
ENDCLASS. "mytest IMPLEMENTATION
Executing Unit Tests:
For program,
For class,
If both the actual and the expected result is same, then Unit test does not find any errors.
In that case one message will be displayed on status bar like,
The task is displayed in a tree structure with a Program name, Class name and method
name. Both the expected and the actual results can be seen in the Unit test results. Also in
the stack it will be displaying the line number where the error occurred. By double clicking
the line number we can enter into the source code.
We can see the ABAP unit results in code inspector. While creating the variant, check for the
ABAP unit in Dynamic check.
In the Code inspector results we can check for the ABAP unit errors, warnings and
informations.
Demo on "Narrow Casting"
Definition: The assignment of a subclass instance to a reference variable of the type
"reference to super class" is described as a narrowing cast, because you are switching from
a more detailed view to a one with less detail. It is also called as up-casting.
A user who is not interested in the finer points of cars, trucks, and busses (but only, for
example, in the fuel consumption and tank gauge) does not need to know about them. This
user only wants and needs to work with (references to) the lcl_vehicle(super class) class.
However, in order to allow the user to work with cars, busses, or trucks, you generally need
a narrowing cast.
1. In narrowing casting the object which is created with reference to the sub class is
assigned to the reference of type super class.
2. Using the super class reference it is possible to access the methods from the object
which are only defined at the super class.
3. This access is also called as generic access as super class is normally called as
general class.
Example:
Here method4 is the specific for the sub class and remaining methods are inherited from the
super class.
Narrowing cast:
REF_VEHICLE = REF_TRUCK.
Accessing methods using super class reference.
1. By the super class reference (REF_VEHICLE) it is possible to access all the methods which
are defined at the super class but the implementations are taken from the sub class.
2. If any method is redefined at the sub class then that method‟s implementation which
exist at the sub class is taken in to consideration.
Like:
Here we can access the implementation which exists at the sub class but not from the super
class.
3. It is not possible to access the methods which only defined in the sub class using the
super class reference.
Go to transaction SE38.
Now execute (F8):
Result:
Abstract Classes and Methods in Object Oriented
Programming
Abstract Class: Classes which contain one or more abstract methods or abstract
properties, such methods or properties do not provide implementation. These abstract
methods or properties are implemented in the derived classes (Sub-classes).
Abstract classes does not create any instances to that class objects
We can define some common functionalities in Abstract class (Super-class) and those can
be used in derived classes (Sub classes).
TCode: SE24
Press enter
Enter the Attribute name, Level, Visibility, Type and Description as shown in the screen
shot.
Go to Methods tab,
Enter Method name, Level, Visibility and Description as shown in the below screen shot
Double click on the Method name "AREA"; it goes to method Implementation screen.
When you click on the "Abstract" check box, pop-up window is displayed,
TCode: SE24
Enter the name of class as 'Z_DEMO_ABS_SUB_CLASS' and press Create Button to create
sub class
A pop-up window is displayed, then select "Class" radio button and
Press enter
It goes to next screen, here you enter the Description of the class and then
Select the inheritance button , to inherit the super class then press button
Enter the Super class name as "Z_DEMO_ABS_CLASS", which is being created earlier and
press button.
The Attributes and methods defined in the super class will automatically come into the sub
class. See the below screen shots.
Go to the Methods tab, select the "AREA" method and click on
"Redefine" button
If you are not Redefine the method and trying to activate the class, it gives syntax error.
Method AREA
....
Endmethod
method AREA
DO 10 TIMES.
IF lv_count <= '10'.
lv_res = v_num * lv_count.
* Displa the multiplication table for a Given Number
WRITE: / v_num,
'*',
lv_count,
'=',
lv_res.
* Increment Count value
lv_count = lv_count + 1.
ELSE.
EXIT.
ENDIF.
ENDDO.
* Clear variable
CLEAR: v_num.
endmethod
Then save and activate the class and method.
Final Class:
TCode: SE24
Press enter
Enter the Description of the class and select the check box "Final" to define the class as
Final class, and then press enter
Enter the Attribute name, Level, Visibility, Type and Description as shown in the screen
shot.
Go to Methods tab,
Enter Method name, Level, Visibility and Description as shown in the below screen shot
Double click on the Method name "METH"; it goes to method Implementation screen.
Endmethod.
It goes to below screen, then enter value under "NUMBER" as "19" and
TCode: SE24
Enter the name of class as 'Z_DEMO_SUP_CLASS' to create super class and then press
"Create" Button
Press enter
Enter the Description of the class and then press enter
Enter the Attribute name, Level, Visibility, Type and Description as shown in the screen
shot.
Go to Methods tab,
Enter Method name, Level, Visibility and Description as shown in the below screen shot
Double click on the Method name "VOLUM"; it goes to method Implementation screen. As
shown below
Go to "Attributes" tab, check the check box "Final" and then press "Change" button.
TCode: SE24
Enter the name of class as 'Z_DEMO_SUB_CLASS' and press Create Button to create sub
class
A pop-up window is displayed, then select "Class" radio button and
Press enter
Enter the Description of the class and then select the inheritance button , to inherit the
super class.
Enter the Super class name as "Z_DEMO_SUP_CLASS", which is being created earlier and
press "Save" button.
The Attributes and methods defined in the super class will automatically come into the sub
class.
If you try to redefine or modify the super class method "VOLUM", go to the Methods tab,
select the "VOLUM" method and click on
"Redefine" button ,
It gives a message like below and not allowed to redefine or modify the method in sub
class.
It goes to below screen, then enter values under "LENGTH, HEIGHT and WIDTH" as "2, 3
and 4" and Press execute button .
The output will be displayed like below.
Same as sub class, you can also execute the super class "Z_DEMO_SUP_CLASS", the same
output will be displayed.
Redefining methods in subclass
Definition: The methods of the super class can be re-implemented at the sub class.
Purpose to redefine methods: if the method implementation at the super class is not
satisfies the requirement of the object which is created with reference to the sub class.
1. The REDEFINITION statement for the inherited method must be in the same
SECTION as the definition of the original method.
2. If you redefine a method, you do not need to enter its interface again in the
subclass, but only the name of the method.
3. In the case of redefined methods, changing the interface (overloading) is not
permitted; exception: Overloading is possible with the constructor
4. Within the redefined method, you can access components of the direct super class
using the SUPER reference.
5. The pseudo-reference super can only be used in redefined methods.
Go to transaction SE38:
Result:
Demo for use of super keyword in redefinition:
Go to transaction SE38.
After execution (F8):
Result:
Handling Data in Excel In-place Display Using BDS
The article demonstrates data handling in excel in-place display using BDS with the help of
a program. The demo program maintains the entries in a database table through an excel
in-place display.
OVERVIEW
MS Excel is the conventional way of storing and maintaining data. Sometimes, user prefers
to display report output in specific MS Excel templates; which contain logos, user specific
table formats, engineering drawings, diagrams and macros. The data modified manually in
these excel templates may be again transferred to SAP for processing.
Excel integration is required due to various reasons like avoiding user training on newly
developed custom programs and screens, use existing data templates, data integration with
legacy system.
BDS (Business Document Services) is a convenient option for excel integration as user
specific MS Excel templates can be stored in it. These templates can be called in an ABAP
program at runtime to display data. Also, the data modified by the user in MS Excel can be
read into ABAP program for processing.
The functionality will be demonstrated through a demo program. The program will display
the content of a custom table in excel in-place display. The user can change the non key
fields displayed and the modified contents will be updated to the table after validation.
1. Defining a B DS Class
A custom BDS class can be defined through transaction SBDSV1 as described below. An
existing BDS class can be used, unless the user wants a separate class for a specific
application.
Design a template as per user requirement in MS Excel. You can embed all static
objects/data to be displayed such as logos, drawings, headers etc in the template, except
the area, where the data will be filled at runtime.
Now, go to „Create‟ tab and double click on table template. It will show a pop up to upload
the MS Excel template.
Enter the „Description‟ for the table template after uploading.
The program will maintain a custom table YSM_AGENTS, which has the following fields.
Initially, the program will display the table contents of YSM_AGENTS in the excel template
uploaded in BDS. The user should be able to modify only the non key fields of the table
filled with color green. So, we need to protect the whole worksheet except a range or
window, which will contain editable fields NAME & EMAIL. The user will not be able to modify
anything else except these fields.
Also, the email entered will be validated. If an invalid email id is entered, error message will
be displayed with the cell to be corrected filled with color red.
Create a screen „0100‟ and a custom control „EXCEL‟ in it to display the excel document in-
place. Also, activate the BACK, EXIT, CANCEL, SAVE options in GUI status.
*&---------------------------------------------------------------------*
*& Report YSM_TEST5
*&---------------------------------------------------------------------*
*& Demo program for displaying table data in a specific excel template
*& using BDS. Also, reads the contents modified by user again into ABAP
*& program after validations and updates the table.
*&---------------------------------------------------------------------*
REPORT ysm_test5.
************************************************************************
* Data Declaration
************************************************************************
* Custom Table With 3 fields
*->AGENTID (KEY)
*->NAME
*->EMAIL
TABLES: ysm_agents.
TYPE-POOLS: soi,
sbdst.
************************************************************************
* Selection Screen
************************************************************************
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME.
* User will enter the agent ids to be modified
SELECT-OPTIONS: s_agent FOR ysm_agents-agentid OBLIGATORY.
************************************************************************
* START OF SELECTION
************************************************************************
START-OF-SELECTION.
* Call Excel Inplace Display
CALL SCREEN 100. "Create a screen 100 with custom container 'EXCEL'
************************************************************************
* SCREEN LOGIC
************************************************************************
*&---------------------------------------------------------------------*
*& Module STATUS_0100 OUTPUT
*&---------------------------------------------------------------------*
MODULE status_0100 OUTPUT.
*&---------------------------------------------------------------------*
*& Module USER_COMMAND_0100 INPUT
*&---------------------------------------------------------------------*
MODULE user_command_0100 INPUT.
CASE sy-ucomm.
WHEN 'BACK' OR 'EXIT' OR 'CANCEL'.
* Close document
PERFORM f_close_document.
LEAVE TO SCREEN 0.
WHEN 'SAVE'.
* Save the modified entries into database
PERFORM f_save_document.
ENDCASE.
************************************************************************
* SUBROUTINES
************************************************************************
*&---------------------------------------------------------------------*
*& Form f_get_table_data
*&---------------------------------------------------------------------*
* Get fresh data from YSM_AGENTS
*----------------------------------------------------------------------*
FORM f_get_table_data .
IF sy-subrc NE 0.
MESSAGE 'No Agent Details Found' TYPE 'E'.
ENDIF.
*&---------------------------------------------------------------------*
*& Form f_open_document
*&---------------------------------------------------------------------*
* Open the table template from BDS
*----------------------------------------------------------------------*
* --> l_clsnam Class Name in OAOR
* --> l_clstyp Class Type in OAOR
* --> l_objkey Object key in OAOR
* --> l_desc Description of the excel template in OAOR
*----------------------------------------------------------------------*
FORM f_open_document USING l_clsnam TYPE sbdst_classname
l_clstyp TYPE sbdst_classtype
l_objkey TYPE sbdst_object_key
l_desc TYPE char255.
IF wf_retcode NE c_oi_errors=>ret_ok.
CALL METHOD c_oi_errors=>raise_message
EXPORTING
type = 'E'.
ENDIF.
IF wf_retcode NE c_oi_errors=>ret_ok.
CALL METHOD c_oi_errors=>raise_message
EXPORTING
type = 'E'.
ENDIF.
IF sy-subrc NE 0.
MESSAGE 'Error Retrieving Document' TYPE 'E'.
ENDIF.
IF wf_retcode NE c_oi_errors=>ret_ok.
CALL METHOD c_oi_errors=>show_message
EXPORTING
type = 'E'.
ENDIF.
* Open Document
CALL METHOD r_proxy->open_document
EXPORTING
document_url = locwa_uris-uri
open_inplace = abap_true
protect_document = abap_true "Protect Document initially
IMPORTING
retcode = wf_retcode.
IF wf_retcode NE c_oi_errors=>ret_ok.
CALL METHOD c_oi_errors=>show_message
EXPORTING
type = 'E'.
ENDIF.
IF wf_retcode NE c_oi_errors=>ret_ok.
CALL METHOD c_oi_errors=>show_message
EXPORTING
type = 'E'.
ENDIF.
*&---------------------------------------------------------------------*
*& Form f_dis_table_data
*&---------------------------------------------------------------------*
* Display data in table template
*----------------------------------------------------------------------*
FORM f_dis_table_data .
DATA: locint_fields TYPE TABLE OF rfc_fields.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
*&---------------------------------------------------------------------*
*& Form f_protect_sheet
*&---------------------------------------------------------------------*
* Protect the whole sheet except the fields to edited
*----------------------------------------------------------------------*
FORM f_protect_sheet .
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ELSE.
* If not protected, protect the sheet
IF loc_protect NE abap_true.
CALL METHOD r_excel->protect
EXPORTING
protect = abap_true
IMPORTING
error = r_error
retcode = wf_retcode.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
ENDIF.
ENDIF.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
* Close document
IF NOT r_proxy IS INITIAL.
CALL METHOD r_proxy->close_document
IMPORTING
error = r_error
retcode = wf_retcode.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
ENDIF.
*&---------------------------------------------------------------------*
*& Form f_save_document
*&---------------------------------------------------------------------*
* Save the modified entries into database table
*----------------------------------------------------------------------*
FORM f_save_document .
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
AT END OF row.
locwa_agents_mod-mandt = sy-mandt.
APPEND locwa_agents_mod TO locint_agents_mod.
CLEAR locwa_agents_mod.
ENDAT.
ENDLOOP.
* Update Table
MODIFY ysm_agents FROM TABLE locint_agents_mod.
COMMIT WORK.
IF sy-subrc EQ 0.
MESSAGE 'DATA UPDATED' TYPE 'S'.
ELSE.
MESSAGE 'DATA NOT UPDATED' TYPE 'E'.
ENDIF.
*&---------------------------------------------------------------------*
*& Form f_validate_email
*&---------------------------------------------------------------------*
* Validate the email id entered
*----------------------------------------------------------------------*
* -->l_email Email Id
*----------------------------------------------------------------------*
FORM f_validate_email USING l_email TYPE c
l_err_row TYPE i.
TYPE-POOLS:sx.
DATA: locwa_address TYPE sx_address.
* Check Email Id
locwa_address-type = 'INT'.
locwa_address-address = l_email.
IF sy-subrc <> 0.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
* Define Range
CALL METHOD r_excel->insert_range
EXPORTING
name = l_range
rows = l_row
columns = l_column
IMPORTING
error = r_error.
IF r_error->has_failed = abap_true.
CALL METHOD r_error->raise_message
EXPORTING
type = 'E'.
ENDIF.
Selection Screen:
Shows error message and highlights the cell to be corrected in red, if an invalid email id is
entered:
Data Changed and Successfully Saved:
Event Handler Technique in Object oriented ABAP
Event is a mechanism by which method of one class can raise method of another class,
without the hazard of instantiating that class. It provides to raise the method (event handler
method) of one class with help of another method in the same or different class (triggering
method).
The below steps is required to have the event handler in the class:-
Now, the above settings are complete for event handler in class. Create an object from the
class containing the event and call the triggering method to raise the event.
By taking the above steps, the following sample examples will demonstrate the event
handler technique in Class.
This example tells that how to raise method, if the triggering method and event handler
method presents in the same class.
METHOD METHOD_EVENT .
SELECT *
FROM LFA1
INTO TABLE IT_LFA1
WHERE LIFNR BETWEEN S_LIFNR_LOW AND S_LIFNR_HIGH.
*transfer the values to another internal table
IT_LFA11 = IT_LFA1.
ENDMETHOD.
After that provide the logic in se38.
REPORT ZCL_EVENT_OPERATION .
*provide data objects
DATA: LFA1 TYPE LFA1,
OBJ TYPE REF TO ZCL_EVENT_OPERATION,
IT_LFA1 TYPE Z_LFA1,
IT_LFA11 TYPE Z_LFA1,
WA_LFA1 TYPE LFA1.
*provide select statement
SELECT-OPTIONS: S_LIFNR FOR LFA1-LIFNR.
*provide create object
START-OF-SELECTION.
CREATE OBJECT OBJ.
*call the method
CALL METHOD OBJ->METHOD_EVENT
EXPORTING
S_LIFNR_LOW = S_LIFNR-LOW
S_LIFNR_HIGH = S_LIFNR-HIGH
IT_LFA1 = IT_LFA1.
*provide attribute value
IT_LFA11 = OBJ->IT_LFA11.
*display the data
LOOP AT IT_LFA11 INTO WA_LFA1.
WRITE:/ WA_LFA1-LIFNR,
WA_LFA1-LAND1,
WA_LFA1-NAME1,
WA_LFA1-ORT01.
ENDLOOP.
Save it, check it, activate it and execute it.
In general, we may come across the scenario where, some dialog processing needs to be
done after transaction “commit work”. It‟s explained here by considering a scenario.
After filling all necessary details in the delivery document, user clicks on “save” button to
create a delivery document. If any dialog processing (like pop-up to fill some details)
required upon successful execution of COMMIT WORK statement. In this case, we can
approach below method.
Create an event handler method in the custom class ZTEST_HANDLER for the event
TRANSACTION_FINISHED of the standard class CL_SYSTEM_TRANSACTION_STATE.
Note: This event gets triggered as soon as the COMMIT WORK gets executed.
To get the control to the CALL_DIALOG method, we need to do SET HANDLER to register
the event in any user exit before transaction COMMIT WORK execution.
Here in this case, I registered event in a BADI, which gets triggered after pressing SAVE
button in the outbound delivery (VL01N/VL02N) and before COMMIT WORK execution.