Date post: | 07-Apr-2018 |
Category: |
Documents |
Upload: | nataraj-bandaru |
View: | 219 times |
Download: | 0 times |
of 77
8/4/2019 ABAPObjectWorkshopCourseNotes
1/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 1
Horst KellerSAP AG
SAP AG
ABAP Objects
Workshop
8/4/2019 ABAPObjectWorkshopCourseNotes
2/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 2
Workshop Goals
Position of ABAP Objects within the R/3 System
Overview of the syntax of ABAP Objects
Working with existing classes and interfaces
Defining classes and interfaces
Creating objects
Reacting to events
Understanding the polymorphism provided by
interfaces and inheritance
ABAP Objects - Introduction
Release 4.6
April 2000
8/4/2019 ABAPObjectWorkshopCourseNotes
3/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 3
This is not a comprehensive course in object-oriented programming
SAPs training class BC404
Workshop Goals
There is more to object-oriented development than justobject-oriented programming. It has logical advantagesthat are independent of the concrete implementation.
The most important (and most time-consuming) part ofa real object-oriented application is the object-orientedmodeling.
8/4/2019 ABAPObjectWorkshopCourseNotes
4/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 4
Contents
Introduction
From Function Groups to Classes
Classes
Objects
Events
Interfaces
Inheritance
Using Global Classes
Exercises
8/4/2019 ABAPObjectWorkshopCourseNotes
5/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 5
Introduction
Object orientation
Objects ABAP Objects
8/4/2019 ABAPObjectWorkshopCourseNotes
6/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 6
Function
Function Function Function Function
Data Data
Data Data
Data
Data
MethodMethodMethod
AttributesAttributes
AbstractionAbstraction
MethodsMethods
Functions and dataData model as anabstraction of the
real world
Software objectsObject model as anabstraction of the
real world
Real-world objects
Object Orientation
Function Function Function
Information systems have traditionally been defined through their functions.Functions and data were always kept apart, and linked using input/outputrelationships.
At the centre of object-oriented methods are objects. Objects represent abstractor concrete aspects of the real world. Their nature and properties are described bytheir structure and their attributes (data), and their behavior is described in a set of
methods (functions). Objects provide a single shell encompassing both their nature and their behavior.
Using objects, you can establish a one-to-one relationship between a real-lifeproblem and its software solution.
Typical objects in a business environment are 'customer', 'order', and 'invoice'.The R/3 System has implemented objects of this type since Release 3.1 in theBusiness Object Repository (BOR). It is intended to integrate the object model ofthe BOR into ABAP Objects.
8/4/2019 ABAPObjectWorkshopCourseNotes
7/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 7
PublicaccessPrivate
access
Privatecomponents
Interface
Publicevents
Publicattributes
Publicmethods
BOOK
Objects
FLIGHT
AirlineFlight number
Flight
Address
Passenger-list
Customer
Objects consist of two layers - an inner and an outer layer:
Public components: The components of the object (for example, attributes, methods, andevents) that are visible externally. Public components can be addressed directly by allusers. The public components of an object form its interface.
Private components: These attributes, methods, and events are only visible within theobject itself.
The aim of object-oriented modeling is to ensure that each class can ensure itsown consistency. This means that data usually belongs to the private section. Theinternal (private) attributes of the object can only be changed by methods of thesame class. The public section usually only contains methods that manipulate thedata.
Each object has an identifier, which differentiates it from other objects with thesame attributes and methods.
8/4/2019 ABAPObjectWorkshopCourseNotes
8/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 8
ABAP Objects
ABAP Objects is an upwards-compatible extensionof the existing ABAP language
You can use existing ABAP statements withinABAP Objects
You can use ABAP Objects within existing programs
ABAP Objects is fully integrated in theABAP Debugger
ABAP Objects is an upwards-compatible extensionof the existing ABAP language
You can use existing ABAP statements withinABAP Objects
You can use ABAP Objects within existing programs
ABAP Objects is fully integrated in theABAP Debugger
Object orientation in ABAP is an extension of the ABAP language that makesavailable the advantages of object-oriented programming, such as encapsulation,interfaces, and inheritance. This helps to simplify applications and make themmore controllable.
ABAP Objects is fully compatible with the existing language, so you can useexisting statements and modularization units in programs that use ABAP Objects,
and can also use ABAP Objects in existing ABAP programs. ABAP Objects has brought stricter syntax in some places that also applies to the
existing language. Although the old forms cannot be forbidden (for compatibilityreasons) you should use the new forms, even when you are not directly usingABAP Objects. For example, you can no longer refer to a ABAP Dictionary typeusing LIKE, you must specify types of interface parameters, and the names ofcomponents in classes can consist only of the characters "A-Z", "0-9, and "_"and are not allowed to begin with a number.
8/4/2019 ABAPObjectWorkshopCourseNotes
9/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 9
From Function Groups to Classes
Instances of function groups as objects
Example: Function group as counter
8/4/2019 ABAPObjectWorkshopCourseNotes
10/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 10
External session
DataFunctionmodule
Function group 1
DataFunctionmodule
Function group 2
Internal session of an ABAP program
ABAP program with data
CALL FUNCTION ...
Instances of Function Groups as Objects
Before Release 4.0, the ABAP components that most closely resembled objectswere function groups and their function modules.
When a function module is called, an instance of its function group is loaded intothe memory area of the internal session. An instance is a real software object . Ifa single ABAP program calls function modules from more than one function group,it will load more than one instance.
The principal difference between 'real' object-orientation and function modules isthat a program can work with instances of several function groups simultaneously,but not with several instances of a single function group. For example, a programmay need to work with several independent counter variables, or process severalorders at once. For this to work, the function group containing the respectivefunction modules would have to be specially programmed to keep the variousinstances apart.
8/4/2019 ABAPObjectWorkshopCourseNotes
11/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 11
Function Group as Counter - Definition
FUNCTION-POOL COUNTER.
DATA COUNT TYPE I.
FUNCTION SET_COUNTER.* Local Interface IMPORTING VALUE(SET_VALUE)
COUNT = SET_VALUE.ENDFUNCTION.
FUNCTION INCREMENT_COUNTER.COUNT = COUNT + 1.
ENDFUNCTION.
FUNCTION GET_COUNTER.
* Local Interface: EXPORTING VALUE(GET_VALUE)GET_VALUE = COUNT.
ENDFUNCTION.
FUNCTION-POOL COUNTER.
DATA COUNT TYPE I.
FUNCTION SET_COUNTER.* Local Interface IMPORTING VALUE(SET_VALUE)
COUNT = SET_VALUE.ENDFUNCTION.
FUNCTION INCREMENT_COUNTER.COUNT = COUNT + 1.
ENDFUNCTION.
FUNCTION GET_COUNTER.
* Local Interface: EXPORTING VALUE(GET_VALUE)GET_VALUE = COUNT.ENDFUNCTION.
The function group COUNTER works as a counter.
It contains a global integer field COUNT and three function modules -SET_COUNTER, INCREMENT_COUNTER, and GET_COUNTER - that workwith the field. Two of the function modules have import and export parameters.These parameters form the data interface of the function group.
In terms of object-orientation, a function group has exclusively private attributes,and exclusively public methods.
8/4/2019 ABAPObjectWorkshopCourseNotes
12/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 12
Function Group as Counter - Call
DATA NUMBER TYPE I VALUE 5.
CALL FUNCTION 'SET_COUNTER' EXPORTINGSET_VALUE = NUMBER.
DO 3 TIMES.CALL FUNCTION 'INCREMENT_COUNTER'.
ENDDO.
CALL FUNCTION 'GET_COUNTER' IMPORTINGGET_VALUE = NUMBER.
DATA NUMBER TYPE I VALUE 5.
CALL FUNCTION 'SET_COUNTER' EXPORTING
SET_VALUE = NUMBER.
DO 3 TIMES.CALL FUNCTION 'INCREMENT_COUNTER'.
ENDDO.
CALL FUNCTION 'GET_COUNTER' IMPORTINGGET_VALUE = NUMBER.
NUMBER has value 8
A program using the function modules in the group cannot access the COUNTfield directly. Instead, operations on the field are fully encapsulated in the functionmodules. The program can only communicate with the function group by callingthe function modules and using their interfaces.
8/4/2019 ABAPObjectWorkshopCourseNotes
13/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 13
External session
Internal session of an ABAP program
DatenDaten... Data
...
FunktionsFunktions --bausteinbaustein
nth instance, class m
DataInterface
1st instance, class m
ABAP program with data
DatenDaten... Data
...
SchnittSchnitt --stellestelle
nth instance, class 1
DataInterface
1st instance, class 1
Classes Generalize Function Groups
In practice, it is very awkward to manage instances within a function group. Consequently, the datais usually stored in the calling program, and the function modules are called to work with it.
This causes a variety of problems. For example, all the programs that use the function modulesmust use the same data structures as the function group itself. If you change the internal datastructure of a function group, you affect a large number of users, and it is often difficult to predictthe implications of the changes.
Another problem is that all users have copies of the data. When you make changes, it is difficult to
ensure consistency (who has a copy of what, and where is it stored?) Working with global data in function groups is too dangerous, since it is almost impossible to
predict when a particular function group will be loaded during a complex transaction.
These problems are solved by classes . Data and functions are defined in classes instead offunction groups. Using classes, an ABAP program can work with any number of runtime instancesbased on the same template.
Instead of loading a single runtime instance of a function group into memory implicitly when afunction module is called, the ABAP program can now generate the runtime instances of classes
explicitly. The individual runtime instances represent unique objects. You address these usingobject references.
8/4/2019 ABAPObjectWorkshopCourseNotes
14/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 14
Classes, References, and Objects
Example: Class as counter
Reference variables
Creating objects
Calling methods
Working with references
8/4/2019 ABAPObjectWorkshopCourseNotes
15/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 15
Example: Class as Counter
CLASS counter DEFINITION.PUBLIC SECTION.
METHODS: set IMPORTING VALUE(set_value) TYPE i,
increment,get EXPORTING
VALUE(get_value) TYPE i.PRIVATE SECTION.
DATA count TYPE i.ENDCLASS.
CLASS counter DEFINITION.PUBLIC SECTION.
METHODS: set IMPORTING VALUE(set_value) TYPE i,
increment,get EXPORTING VALUE(get_value) TYPE i.
PRIVATE SECTION.DATA count TYPE i.
ENDCLASS. CLASS counter IMPLEMENTATION. METHOD set.
count = set_value.ENDMETHOD. METHOD increment.
count = count + 1.ENDMETHOD. METHOD get.
get_value = count.ENDMETHOD.
ENDCLASS.
CLASS counter IMPLEMENTATION. METHOD set.
count = set_value.ENDMETHOD. METHOD increment.
count = count + 1.ENDMETHOD. METHOD get.
get_value = count.ENDMETHOD.
ENDCLASS.
Let us examine the above class COUNTER.
The class COUNTER works as a counter. It is an object oriented reflection of thefunction group COUNTER that we saw in the last section.
It contains three public methods - SET, INCREMENT, and GET, all of which workwith the private integer field COUNT.
You can call the methods from outside the class. Two methods have input and output parameters. These parameters define the
data interface of the class.
The field COUNT is not visible externally. It represents the encapsulated state ofthe counter.
You will find the details about defining classes in the next chapter.
8/4/2019 ABAPObjectWorkshopCourseNotes
16/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 16
Reference Variables
DATA: cnt_1 TYPE REF TO counter.DATA: cnt_1 TYPE REF TO counter.
CNT_1
In order to create an object of a class you need a reference variable first (here:CNT_1 ).
For declaing reference variables, a new data type REF TO isintroduced.
Reference variables contain object references .
Object references are pointers to objects. In ABAP, they can only be containedin reference variables .
Reference variables use reference semantics .
When assigning one reference variable to another, with reference semantics, youmerely pass the address of the object but not its attributes.
In a program, you can only address an object using a reference variable thatpoints to the object.
Instance-bound components of an object can only be adressed using a referencevariable that points to the object.
An object attribute can also be a reference variable.
8/4/2019 ABAPObjectWorkshopCourseNotes
17/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 17
Creating an Object
DATA: cnt_1 TYPE REF TO counter.
CREATE OBJECT cnt_1 TYPE counter.
DATA: cnt_1 TYPE REF TO counter.
CREATE OBJECT cnt_1 TYPE counter.
CNT_1
1
An object is an instance of a class. Each object has a unique identifier and itsown attributes. All objects exist in the internal session of an ABAP program. Aclass may have any number of instances (objects).
Once you have declared a reference variable with reference to a class, you cancreate an instance of the class (an object). To do this, use the CREATE OBJECT . The reference variable now contains a reference to the object.
The names of the instances are shown in the same format as the contents ofreference variables in the ABAP Debugger. The value of the number is arbitrary.
To distinguish them from classes, instances are displayed with rounded corners.See next chapter for an explanation of the symbols.
Each class always contains implicitly the reference variable ME. The referencevariable ME contains in objects a reference pointing at the object itself and,therefore, is called self reference.
When working in methods with attributes of the own class, you do not need tospecify a reference variable. The system uses the self reference MEautomatically.
8/4/2019 ABAPObjectWorkshopCourseNotes
18/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 18
Calling Methods
DATA: cnt_1 TYPE REF TO counter.
DATA number TYPE I VALUE 5.
CREATE OBJECT cnt_1 TYPE counter.
CALL METHOD cnt_1->setEXPORTING set_value = number.
DO 3 TIMES.CALL METHOD
cnt_1->increment.ENDDO.
CALL METHOD cnt_1->getIMPORTING get_value = number.
DATA: cnt_1 TYPE REF TO counter.
DATA number TYPE I VALUE 5.
CREATE OBJECT cnt_1 TYPE counter.
CALL METHOD cnt_1->setEXPORTING set_value = number.
DO 3 TIMES.CALL METHOD
cnt_1->increment.ENDDO.
CALL METHOD cnt_1->getIMPORTING get_value = number.
CNT_1
1
NUMBER has the value 8
You call a method with CALL METHOD.
You must specify the name of the method and an object. The method then workswith the attributes of that object.
The syntax is: CALL METHOD ref->meth.
ref is a reference variable pointing to an object and meth is a method defined in
the class of that object. The operator -> is called the object component selector . You can also access methods dynamically using the normal parenthetical
semantics (dynamic invocation). Unlike calling subroutines and function modulesdynamically, this also allows you to pass parameters and handle exceptionsdynamically .
8/4/2019 ABAPObjectWorkshopCourseNotes
19/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 19
Several Reference Variables
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CNT_1
CNT_2
CNT_3
This creates a series of reference variables with reference to the same class.
8/4/2019 ABAPObjectWorkshopCourseNotes
20/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 20
Several Objects
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.CREATE OBJECT: cnt_1,
cnt_2.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT : cnt_1,
cnt_2.
CNT_1
CNT_2
CNT_3
2
1
You can create any number of instances of the same class in a program. They arefully independent of each other, and have their own identity and attributes with theprogram. Each CREATE OBJECT statement creates a new object.
8/4/2019 ABAPObjectWorkshopCourseNotes
21/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 21
Assigning Reference Variables
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3 .
CNT_1
CNT_2
CNT_3
2
1
You can assign references between reference variables using the MOVEstatement. This means that the references in more than one reference variablecan point to the same object. When you assign reference variables to each other,their types must be either compatible or convertible.
In the cnt_3 = cnt_2 statement, both class references must have the sametype, that is, refer to the same class. Alternatively, the class of cnt_3 must be a
superclass of the class cnt_2 . You can use reference variables with the type OBJECT as containers for passing
references, because the class OBJECT is superclass to all classes in ABAPObjects.
You cannot use reference variables of type superclass for a static access ofaddititional components in subclasses. Nevertheless, a dynamic method call(dynamic invoke) is always possible.
8/4/2019 ABAPObjectWorkshopCourseNotes
22/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 22
Deleting Reference Variables
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2 .
CNT_1
CNT_2
CNT_3
2
1
Like other variables, you can initialize a reference variable with the CLEARstatement.
The initial value of a reference variable is a reference that does not point to anobject.
8/4/2019 ABAPObjectWorkshopCourseNotes
23/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 23
Garbage Collection
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2.
cnt_3 = cnt_1.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2.
cnt_3 = cnt_1 .
CNT_1
CNT_2
CNT_3
2
1
Garbage collection is a mechanism that ensures that memory space that is nolonger required is automatically released.
The memory space occupied by an object can be released when there are nomore references pointing to the object.
8/4/2019 ABAPObjectWorkshopCourseNotes
24/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 24
Garbage Collection
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2.
cnt_3 = cnt_1.
CLEAR cnt_3.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2.
cnt_3 = cnt_1.
CLEAR cnt_3.
CNT_1
CNT_2
CNT_3
1
Only the reference in CNT_1 now points to an object.
8/4/2019 ABAPObjectWorkshopCourseNotes
25/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 25
3
New Objects
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2.
cnt_3 = cnt_1.
CLEAR cnt_3.
CREATE OBJECT: cnt_2,
cnt_3.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2.
MOVE cnt_2 TO cnt_3.
CLEAR cnt_2.
cnt_3 = cnt_1.
CLEAR cnt_3.
CREATE OBJECT: cnt_2,
cnt_3.
CNT_1
CNT_2
CNT_3
2
1
Using the CREATE OBJECT statement, the example creates new objects towhich the references in CNT_2 and CNT_3 are pointing.
The program would have had the state depicted on the right-hand side, evenwithout the CLEAR CNT_3 statement, since the CREATE OBJECT statementalways creates a new object and overwrites the previous contents of the classreference with the new reference.
8/4/2019 ABAPObjectWorkshopCourseNotes
26/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 26
3
Methods of Several Objects
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.
CREATE OBJECT: cnt_1,
cnt_2,
cnt_3.
CALL METHOD cnt_1->setEXPORTING set_value = 1.
CALL METHOD cnt_2->set
EXPORTING set_value = 10.
CALL METHOD cnt_3->setEXPORTING set_value = 100.
DATA: cnt_1 TYPE REF TO counter,
cnt_2 TYPE REF TO counter,
cnt_3 TYPE REF TO counter.CREATE OBJECT: cnt_1 ,
cnt_2 ,
cnt_3 .
CALL METHOD cnt_1 ->setEXPORTING set_value = 1.
CALL METHOD cnt_2 ->set
EXPORTING set_value = 10.CALL METHOD cnt_3 ->set
EXPORTING set_value = 100.
CNT_1
CNT_2
CNT_3
2
1
The value of COUNT isdifferent in each object
The same method is called in different objects.
Each object has its own attributes and the method works with the respectiveattributes for each individual object.
8/4/2019 ABAPObjectWorkshopCourseNotes
27/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 27
Declaring reference variables
Creating objects
Accessing attributes and methods
DATA: ref1 TYPE REF TO class,ref2 TYPE REF TO class.DATA: ref1 TYPE REF TO class,ref2 TYPE REF TO class.
CREATE OBJECT: ref1, ref2.CREATE OBJECT : ref1, ref2.
x = ref1->attr + ref2->attr.CALL METHOD ref1->method EXPORTING ...x = ref1 -> attr + ref2 -> attr.CALL METHOD ref1 -> method EXPORTING ...
Objects: Summary
As well as using the CALL METHOD statement, you can also call methods byusing them in place of operands in arithmetical or logical expressions.
You must use functional methods to do this. A functional method is a methodwith only one returning parameter (see next chapter).
Then, method calls can be written as follows:
No IMPORTING parameters: meth( ) One IMPORTING parameter: meth( f1 )
meth( p1 = f1 )
n IMPORTING parameters: meth( p1 = f1 ... pn = fn )
8/4/2019 ABAPObjectWorkshopCourseNotes
28/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 28
Classes in Detail
Structure of classes
Components of classes
Accessing the components
8/4/2019 ABAPObjectWorkshopCourseNotes
29/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 29
Class c1Class c1
All usersAll users
Private
componentsa3 , m3,e3
Methodimplementations
Protected componentsa2, m2, e2,
Public
components
a1, m1,e1
CLASS c1 DEFINITION.PUBLIC SECTION.
DATA: a1 METHODS: m1 EVENTS: e1
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS c1 IMPLEMENTATION.
METHOD m1. ENDMETHOD. METHOD m2. ENDMETHOD.
METHOD m3. ENDMETHOD.
ENDCLASS.
Subclasses of c1
Structure of Classes - Visibility Sections
DATA: a2 METHODS: m2 EVENTS: e2
DATA: a3 METHODS: m3 EVENTS: e3
Classes are templates for objects.
You can either declare them locally in any ABAP program, or globally in the R/3Repository using the Class Builder in the ABAP Workbench.
A class definition consists of a declaration part and an implementation part.
The class consists of components. All components are declared in the declarationpart of the class. They define the attributes of the class. Each component must be
declared in one of the three visibility sections of the class declaration. This definesthe external interface of the class. Within a class, all components are visible.The three visibility sections are:
PUBLIC - All components declared in the public section can be addressed within the class andfrom outside. The public section forms the external interface of the class.
PROTECTED - Protected components can be addressed in the methods of the class and itssubclasses..
PRIVATE - Private components can only be addressed in the methods of the class in whichthey are declared.
Any methods that you declare in a class must also be implemented in itsimplementation part.
The left-hand side of the diagram shows the declaration and implementation partsof a local class c1. The right-hand side shows the practical consequence of thestructure of the class, with the components belonging to various visibility sections,and the method im lementations.
8/4/2019 ABAPObjectWorkshopCourseNotes
30/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 30
CLASS ... DEFINITION....... SECTION.
DATA ... TYPE ... [READ-ONLY] ...CLASS-DATA ... TYPE ... [READ-ONLY] ...CONSTANTS ... TYPE ... VALUE ......
ENDCLASS.
CLASS ... DEFINITION....... SECTION.
DATA ... TYPE ... [READ-ONLY] ...CLASS-DATA ... TYPE ... [READ-ONLY] ...CONSTANTS ... TYPE ... VALUE ......
ENDCLASS.
Components of Classes: Attributes
DATA: Instance attributes
CLASS-DATA: Static attributes CONSTANTS: Constants
Attributes are data objects within a class. They can have any ABAP data type.
The contents of the attributes of an object determine its state.
The contents of the instance attributes (DATA) of a class determine the state ofan instance.
The contents of the static attributes (CLASS-DATA) of a class determine the
state of the class that applies to all instances. There is one set of instanceattributes that is shared by the whole class.
The READ-ONLY attribute allows you to make the public attributes of a classvisble externally, but they may then only be changed within the methods of theclass.
Constants (declared using CONSTANTS ) are special static attributes. You specifytheir value when you declare them, and this may not subsequently be changed.
8/4/2019 ABAPObjectWorkshopCourseNotes
31/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 31
Static Attributes and Instance Attributes
DATA: cref TYPE REF TO c.
WRITE c=>a1.
CREATE OBJECT cref TYPE c.
WRITE cref->a2.
DATA: cref TYPE REF TO c.
WRITE c=> a1.
CREATE OBJECT cref TYPE c.
WRITE cref-> a2.
CREF
1
a2...
CLASSa1
...
CLASSa1
...
CLASS c DEFINITION.PUBLIC SECTION.
...CLASS-DATA a1(10) TYPE C
VALUE 'Static'.DATA a2(10) TYPE C
VALUE 'Instance'....
ENDCLASS.
CLASS c DEFINITION.PUBLIC SECTION.
...CLASS-DATA a1(10) TYPE C
VALUE 'Static'.DATA a2(10) TYPE C VALUE 'Instance'.
...ENDCLASS.
Static attributes are independent of instances in the internal session of an ABAPprogram.
They are created when a class is accessed for the first time.
You can access static attributes with the class name and the class componentselector =>.
Instance attributes are created exclusively with the CREATE OBJECT statementand you can access them only with reference variables.
You can also access static attributes using object references. However, therevalue is independent of the object to which the reference is pointing.
When methods in different objects but from the same class access a staticattribute of that class, they also work with the same data object.
8/4/2019 ABAPObjectWorkshopCourseNotes
32/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 32
CLASS ... DEFINITION....... SECTION.
METHODS ... IMPORTING [VALUE] ... TYPE ... [OPTIONAL]EXPORTING [VALUE] ... TYPE ...CHANGING [VALUE] ... TYPE ... [OPTIONAL]RETURNING VALUE(...) TYPE ...EXCEPTIONS ...
CLASS-METHODS ......
ENDCLASS.
CLASS ... DEFINITION....... SECTION.
METHODS ... IMPORTING [VALUE] ... TYPE ... [OPTIONAL]EXPORTING [VALUE] ... TYPE ...CHANGING [VALUE] ... TYPE ... [OPTIONAL]RETURNING VALUE(...) TYPE ...EXCEPTIONS ...
CLASS-METHODS ......
ENDCLASS.
CLASS ... IMPLEMENTATION. METHOD ...
...ENDMETHOD.
ENDCLASS.
CLASS ... IMPLEMENTATION. METHOD ...
...ENDMETHOD.ENDCLASS.
Components of Classes: Methods
METHODS : Instance methods
CLASS-METHODS: Static methods
Methods are internal procedures within a class. They can access all the attributes in a class, andcan therefore change the state of an object.
They have a parameter interface. This allows them to receive values from and return values totheir caller. Methods may contain declarations of local data types and objects. Local data andinterface parameters, that are treated like local variables, obscure those class attributes that havethe same names.
Instance methods (METHODS) can access all the attributes in a class, and can trigger all of the
events in the class. Static methods (CLASS-METHODS) can only access the static attributes of a class, and can only
trigger static events.
Each method in a class must be implemented in the implementation part of the class definition. Theimplementation is enclosed between the METHOD and ENDMETHOD statements. The parameterinterface must not be named during the method implementation, but only during the methoddeclaration.
You call a method using the CALL METHOD statement. This has the same syntax as CALLFUNCTION.
Functional methods are methods with any number of IMPORTING parameters and oneRETURNING parameter. The RETURNING parameter is always passed by value. Besides callingfunctional methods with CALL METHOD, you can replace variables with functional methods inexpressions.
As in function modules, you can use the statements RAISE and MESSAGE RAISINGin methods to handle exceptional situations.
8/4/2019 ABAPObjectWorkshopCourseNotes
33/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 33
CLASS c DEFINITION.PUBLIC SECTION.
METHODS CONSTRUCTOR [IMPORTING arg1 TYPE type ... ].
CLASS-METHODS CLASS_CONSTRUCTOR.
ENDCLASS.
CLASS c DEFINITION.PUBLIC SECTION.
METHODS CONSTRUCTOR [IMPORTING arg1 TYPE type ... ].
CLASS-METHODS CLASS_CONSTRUCTOR .
ENDCLASS.
CLASS c IMPLEMENTATION. METHOD CONSTRUCTOR.
...ENDMETHOD. METHOD CLASS_CONSTRUCTOR.
...
ENDMETHOD.ENDCLASS.
CLASS c IMPLEMENTATION. METHOD CONSTRUCTOR .
...ENDMETHOD. METHOD CLASS_CONSTRUCTOR .
...
ENDMETHOD.ENDCLASS.
PROGRAM .
DATA o1 TYPE REF TO c.CREATE OBJECT o1 EXPORTING arg1 = v1 ...
PROGRAM .
DATA o1 TYPE REF TO c.CREATE OBJECT o1 EXPORTING arg1 = v1 ...
Constructors
The constructors CONSTRUCTOR and CLASS_CONSTRUCTOR are special methods that arecalled implicitly when you create an object (CONSTRUCTOR) or when you first access a class(CLASS_CONSTRUCTOR).
Constructors cannot be called using CALL METHOD. Instead, they are automatically called by thesystem to define the initial state of an object or class
A class can have an instance constructor, which is called automatically in the CREATE OBJECTstatement after the object has been created, and a static constructor, which is automatically called
before the first access to the class. These methods have the reserved names CONSTRUCTOR and CLASS_CONSTRUCTOR
respectively.
An instance constructor can only have IMPORTING parameters. Static constructors have noparameters. You must fill the IMPORTING parameters of the instance constructor in the CREATEOBJECT statement.
Constructors are necessary whenever you need to set the initial state of an object dynamically, andthe VALUE addition of the DATA statement is insufficient.
The constructors are always present, even if you do not declare them explicitly. The explicitdeclaration is only necessary when you want to implement a constructor for a class.
8/4/2019 ABAPObjectWorkshopCourseNotes
34/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 34
class=>compclass=>comp
ref>compref>comp
Accessing the components of classes
Instance components
Instance attribute ref->attr
Instance method: call method ref->meth Static components
Static attribute: class=>attr
Static method: call method class=>meth
Special references in methods
Self reference: ME->compPseudo reference SUPER->comp
n
...
ME
To access a component from the inside, meaning in a method of the same class,you need only the components name. The self reference ME is used implicitly.
To access a component from the outside, for instance components you mustname the object with the object component selector -> and for static componentsthe class with the class component selector =>. .
When accessing components from the inside, special references are possible:
Explicit use of the self reference: ME->attrCALL METHOD ME->meth
Call of the superclass methodduring method redefinition: CALL METHOD SUPER->meth
You can access methods dynamically using the normal parenthetical semantics(dynamic invocation) :
CALL METHOD ref->(name) PARAMETER-TABLE ptabEXCEPTION-TABLE etab.
Unlike calling subroutines and function modules dynamically, this also allows youto pass parameters and handle exceptions dynamically .
8/4/2019 ABAPObjectWorkshopCourseNotes
35/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 35
Inheritance
Introduction
Overview
Single inheritance
Redefining methods
Example: Subclass of superclass counter
8/4/2019 ABAPObjectWorkshopCourseNotes
36/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 36
nclass1
CREF3
CREF2
CREF1
class2
class3
Inheritance: Introduction
Definition of a class by inheriting the components from asuperclass (Reuse)
Specialization by adding own components and redefining
methods in subclasses Polymorphism by accessing subclass objects
Inheritance allows you to derive subclasses from superclasses.
Subclasses contain the attributes, methods and events of all their superclasses.
You can add new components in each subclass or re-implement existingmethods.
Reference variables, that have the type of a superclass can point to subclass
objects. Above, three reference variables of different type point to an object of class
CLASS3 which is a subclass of superclasses CLASS2 and CLASS1.
8/4/2019 ABAPObjectWorkshopCourseNotes
37/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 37
Class c1CLASS c1 DEFINITION INHERITING FROM ......
ENDCLASS.
CLASS c1 IMPLEMENTATION....
ENDCLASS.
CLASS c2 DEFINITION INHERITING FROM c1....ENDCLASS.
CLASS c2 IMPLEMENTATION....
ENDCLASS.
Class c2
Class OBJECT
Class ...
...
...
Inheritance - Overview
Inheritance allows you to derive new classes from existing ones.
The new class adopts (inherits) all components of the existing class. The newclass is known as the subclass, the existing class as the superclass.
The coding of superclasses is reused in subclasses.
Only the components of the public and protected sections of the superclass are
visible in its subclasses. You can define extra components in the subclass, making it more specialized than
the superclass. A subclass of a class can also become a superclass of a furthernew class. This allows you to introduce several degrees of specialization.
Like all components, static attributes exist only once in each branch of aninheritance tree. A subclass can access the content of the public and protectedstatic attributes of all superclasses. Conversely, a superclass shares its public andprotected static attributes with all subclasses. Thus static attributes are notassigned to one single class but to a branch of the inheritance tree. They arevisible and modifiable in all classes involved. Changes can be made from outsideusing the class component selector => with all class names involved or frominside in all associated classes.
8/4/2019 ABAPObjectWorkshopCourseNotes
38/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 38
C1 ...
OBJECT
C2...
...
Single Inheritance
Classes can have several direct subclasses, but only a single superclass. ABAPObjects thus only supports single inheritance.
When a subclass inherits from a superclass that is itself a subclass of anotherclass, the classes involved form an inheritance tree, which becomes morespecialized as we move from top to bottom. Conversely, superclasses can beseen as generalizations of subclasses.
The root node of all ABAP Objects inheritance trees is the predefined classOBJECT. This is an implicit class - you do not have to specify it as the superclassof every new class in ABAP Objects.
In the inheritance tree, all nodes higher than the current one are superclasses. Allthose below the current level are subclasses.
The declaration of subclass components is distributed over all superclasses of therespective branch of the inheritance tree.
It is always possible to assign the contents of a reference variable defined with
reference to a subclass to a reference variable defined with reference to one of itssuperclasses or interfaces. Above all, you can always specify the class OBJECTfor the target variable.
Statically , users can only address the known components of a class. Redefiningmethods within subclasses is one of the bases for polymorphism .
Dynamic method calls allow users to address specializations within subclasses.
8/4/2019 ABAPObjectWorkshopCourseNotes
39/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 39
CLASS ... DEFINITION INHERITING FROM ...
... SECTION. METHODS ... REDEFINITON ......
...
ENDCLASS.
CLASS ... DEFINITION INHERITING FROM ...
... SECTION. METHODS ... REDEFINITON ......
...
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ......
ENDMETHOD.
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ......
ENDMETHOD.
ENDCLASS.
Redefining Methods
Semantic rules
Subclasses must behave just like their superclass for allusers of inherited components
A redefined method must observe the original semantics
Inheritance should only be used to specialize
Each subclass contains the components of all classes that appear in theinheritance tree between it and the root node. The visibility of a component alwaysremains the same and cannot be changed.
You can specialize the public and protected instance methods of all precedingsuperclasses by redefining them using the REDEFINITION addition of theMETHODS statement.
You cannot change the interface of a redefined method. Redefined methods aremerely implemented differently under the same name.
Within a redefined method, you can use the pseudoreference SUPER to accessthe method with the same name in the superclass, for example, to adopt andextend its functions.
The additions ABSTRACT and FINAL of the METHODS and CLASS statementsallow you to define abstract and final methods and classes.
Abstract methods are defined in abstract classes, and cannot be implemented inthe same class. Instead, they have to be implemented in a subclass. You cannotinstantiate an abstract class.
You cannot redefine a final method in a subclass. Final classes cannot have anyfurther subclasses, and therefore conclude an inheritance tree.
8/4/2019 ABAPObjectWorkshopCourseNotes
40/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 40
CLASS subclass DEFINITION INHERITING FROM superclass.PUBLIC SECTION.
METHODS CONSTRUCTOR IMPORTING ......
ENDCLASS.
CLASS subclass DEFINITION INHERITING FROM superclass.PUBLIC SECTION.
METHODS CONSTRUCTOR IMPORTING ......
ENDCLASS.CLASS subclass IMPLEMENTATION.
METHOD CONSTRUCTOR....CALL METHOD SUPER->CONSTRUCTOR EXPORTING ......
ENDMETHOD....
ENDCLASS.
CLASS subclass IMPLEMENTATION. METHOD CONSTRUCTOR.
...CALL METHOD SUPER->CONSTRUCTOR EXPORTING ......
ENDMETHOD....
ENDCLASS.
PROGRAM ...
DATA o1 TYPE REF TO subclass.CREATE OBJECT o1 TYPE subclass EXPORTING ...
PROGRAM ...
DATA o1 TYPE REF TO subclass.CREATE OBJECT o1 TYPE subclass EXPORTING ...
Access to staticattributes only
Accress to instance
attributes also
Inheritance and Constructors
There are special rules for constructors in inheritance.
You cannot redefine the instance constructor of a superclass in its subclasses. An instance constructor of a subclass must contain the method call CALL METHOD SUPER-
>CONSTRUCTOR , which calls the instance constructor of its direct superclass. The only exception tothis rule are the subclasses of the root node of the inheritance tree OBJECT .
In subclasses that do not have an explicitly-defined instance constructor, an implicit constructor(which always exists) is executed that automatically calls the instance constructor of the immediatesuperclass.
When you call an instance constructor with CREATE OBJECT or CALL SUPER->CONSTRUCTOR ,you must assign values to all non-optional interface parameters of the next-highest explicitinstance constructor in the hierarchy .
The instance constructor of a subclass is divided into two parts by the required CALL METHODSUPER->CONSTRUCTOR . In the statements before the SUPER->CONSTRUCTOR call, theconstructor behaves like a static method, that is, it cannot access the instance attributes of itsclass. After the call, however, it can also address the instance attributes.
The first time you address a subclass in a program, the static constructor is called. Before this,however, all static constructors further up the entire inheritance tree must also have beenexecuted. Bearing in mind that a static constructor can only be called once during the runtime of aprogram, the system searches for the next-highest superclass in the inheritance hierarchy whosestatic constructor has not yet been called. It then calls this static constructor and those of all of itssubclasses down to the subclass that you addressed.
8/4/2019 ABAPObjectWorkshopCourseNotes
41/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 41
Subclass for Superclass Counter*
CLASS counter_ten DEFINITION INHERITING FROM counter.PUBLIC SECTION.
METHODS increment REDEFINITION.DATA count_ten.
ENDCLASS.
CLASS counter_ten DEFINITION INHERITING FROM counter .PUBLIC SECTION.
METHODS increment REDEFINITION .DATA count_ten.
ENDCLASS. CLASS counter_ten IMPLEMENTATION. METHOD increment.
DATA modulo TYPE I.CALL METHOD super->increment. modulo = count mod 10.IF modulo = 0.
count_ten = count_ten + 1.ENDIF.
ENDMETHOD.ENDCLASS.
CLASS counter_ten IMPLEMENTATION. METHOD increment.
DATA modulo TYPE I.CALL METHOD super->increment . modulo = count mod 10.IF modulo = 0.
count_ten = count_ten + 1.ENDIF.
ENDMETHOD.ENDCLASS.
DATA: count TYPE REF TO counter.
CREATE OBJECT count TYPE counter_ten.CALL METHOD count->set EXPORTING set_value = number.DO 10 TIMES.
CALL METHOD count->increment.ENDDO.
DATA: count TYPE REF TO counter .
CREATE OBJECT count TYPE counter_ten .CALL METHOD count->set EXPORTING set_value = number.DO 10 TIMES.
CALL METHOD count->increment.ENDDO.
PROTECTED SECTION.DATA count TYPE I.
PROTECTED SECTION.DATA count TYPE I.
*Replace PRIVATE with:
The class CL_COUNTER_TEN is derived from class COUNTER. It redefines themethod INCREMENT.
To achieve this, the COUNT attribute must be moved from the private section ofCOUNTER to the protected section. The subclass influences the superclass!.
The redefined method calls the obscured method of the superclass using thepseudoreference SUPER->.
The redefinition of the method specializes the inherited method.
An object of (dynamic) type subclass is created and a reference variable of (static)type superclass is pointing to it.
When you call method INCREMENT via a superclass reference in a subclassobject, the redefined method of the subclass is executed.
That is what polymorphism means. You acces an object with a reference variable
of one type but the object itself has another type.
8/4/2019 ABAPObjectWorkshopCourseNotes
42/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 42
Interfaces
Introduction
Overview
Definition
Implementation
Interface references
Example: Interface for counter
8/4/2019 ABAPObjectWorkshopCourseNotes
43/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 43
n
n
niref_line
iref_line
iref_line
iref_tab
Interface
Interfaces: Introduction
Definition of an interface without implementation
Classes can implement several interfaces
Uniform access with interface references
Polymorphism independent from inheritance
Interfaces are defined independently of classes.
They contain declarations for attributes, methods and events.
Classes can implement interfaces.
Such classes expose an uniform point of contact to the public and are obliged toprovide the functions of the interfaces by implementing their methods.
You can type reference variables referring to interfaces, but there are noinstances of interfaces.
Interface references can point to objects of different classes.
Above, an internal table has the line type of an interface reference variable andcontains references to objects of different classes, all of them implementing therespective interface.
8/4/2019 ABAPObjectWorkshopCourseNotes
44/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 44
Class c1Class c1
Privatecomponents
a2, m2,e2
Methodimplementations
Protected componentsa3, m3, e3,
Publiccomponents
CLASS c1 DEFINITION.PUBLIC SECTION.
INTERFACES i1 ...DATA a1 ...
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS c1 IMPLEMENTATION.
METHOD i1~m1 . ENDMETHOD.
ENDCLASS.
INTERFACE i1.DATA: a1 ... METHODS: m1 ...EVENTS: e1 ...
ENDINTERFACE .
i1~a1,i1~m1,...
a1,...
Interfaces - Overview
All usersAll users Subclasses of c1
The public components of a class define the external point of contact for the class.
Interfaces are independent structures that allow you to extend this public point ofcontact or define it fully for a particular class. They allow you to address differentclasses in a uniform way. The left-hand side of the diagram shows the definition ofa local interface i1 and the declaration and implementation parts of a local classc1, which implements the interface i1 in its public section. The interface method
i1~m1 must be implemented in the implementation part of the class. The right-hand side shows the structure of the class, composed of the
components of each visibility section and the method implementations. Theinterface components extend the external face of the class. All users can accessboth the class-specific public components and the components of the interface.
Interfaces, along with inheritance, provide the basis for the polymorphism ofclasses, since a method of an interface can be implemented in different ways indifferent classes.
One class can implement several parallel interfaces.
8/4/2019 ABAPObjectWorkshopCourseNotes
45/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 45
INTERFACE ... ....DATA: ... TYPE ... [READ-ONLY] ...CLASS-DATA: ... TYPE ... [READ-ONLY] ...
CONSTANTS: ... TYPE ... [VALUE ...]
METHODS: ... IMPORTING [VALUE] ... TYPE ... [OPTIONAL]EXPORTING [VALUE] ... TYPE ...CHANGING [VALUE] ... TYPE ... [OPTIONAL]RETURNING VALUE(...) TYPE ...EXCEPTIONS ...
CLASS-METHODS: ...
EVENTS: ... [EXPORTING VALUE(...) TYPE ... [OPTIONAL]].CLASS-EVENTS:...
INTERFACES: ...
ENDINTERFACE.
INTERFACE ... ....DATA: ... TYPE ... [READ-ONLY] ...CLASS-DATA: ... TYPE ... [READ-ONLY] ...
CONSTANTS: ... TYPE ... [VALUE ...]
METHODS: ... IMPORTING [VALUE] ... TYPE ... [OPTIONAL]EXPORTING [VALUE] ... TYPE ...CHANGING [VALUE] ... TYPE ... [OPTIONAL]RETURNING VALUE(...) TYPE ...EXCEPTIONS ...
CLASS-METHODS: ...
EVENTS: ... [EXPORTING VALUE(...) TYPE ... [OPTIONAL]].CLASS-EVENTS:...
INTERFACES : ...
ENDINTERFACE .
Interfaces - Definition
Like classes, you can define interfaces either globally in the R/3 Repository, orlocally within an ABAP program.
They can contain the same components as classes (attributes, methods, events,and constants). However, the methods are not implemented in the interface itself,but rather in the classes that implement it.
You do not have to assign the components of interfaces to a visibility area.Instead, all components automatically belong to the public section of the classimplementing the interface.
Interfaces allow you to define components that are common to several classes atone central point. When a class implements an interface, it must also implementall of its methods.
The methods of an interface are abstract, since they can be implementeddifferently in each class.
You can nest interfaces using the INTERFACES statement between the
INTERFACE and ENDINTERFACE statements. For implementation, thecomponents of a nested interface all belong to the same level, so a nestedinterface only contains one instance of each interface component, even if acomponent interface is itself a component of another component interface.
You can define ALIASES for components of compound interfaces.
8/4/2019 ABAPObjectWorkshopCourseNotes
46/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 46
CLASS ... DEFINITION.
PUBLIC SECTION.INTERFACES: ......
...
ENDCLASS.
CLASS ... DEFINITION.
PUBLIC SECTION.INTERFACES : ......
...
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ...~......
ENDMETHOD.
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ... ~ ...
...ENDMETHOD.
ENDCLASS.
Interfaces - Implementation
Unlike classes, interfaces do not have instances. Instead, they are implementedby classes in the public visibility section.
When you implement an interface in a class, the components of the interface areadded to the components of the public section of the class. To address acomponent comp of an interface intf , use the name intf~comp . Thecomponents of implemented interfaces are fully equivalent to normal components
of the class. The class must implement all methods of the interface itself in its implementation
part:METHOD intf~imeth - ENDMETHOD.
An interface can be implemented by several classes, each of which is extendedby the same set of components. The methods of the interface can beimplemented differently in each implementing class.
You can define ALIASES for the components of implemented interfaces.
8/4/2019 ABAPObjectWorkshopCourseNotes
47/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 47
INTERFACE i1....
ENDINTERFACE.
CLASS c1 DEFINITION.PUBLIC SECTION.
DATA a1.INTERFACES i1.
ENDCLASS.
CLASS c2 DEFINITION.PUBLIC SECTION.
INTERFACES i1.ENDCLASS.
DATA cnt_c TYPE REF TO c1.DATA: cnt_1 TYPE REF TO i1,
cnt_2 LIKE cnt_1.
CREATE OBJECT: cnt_c TYPE c1,cnt_1 TYPE c2.
MOVE cnt_c to cnt_2.
INTERFACE i1....
ENDINTERFACE.
CLASS c1 DEFINITION.PUBLIC SECTION.
DATA a1.INTERFACES i1.
ENDCLASS.
CLASS c2 DEFINITION.PUBLIC SECTION.
INTERFACES i1.ENDCLASS.
DATA cnt_c TYPE REF TO c1.DATA: cnt_1 TYPE REF TO i1,cnt_2 LIKE cnt_1.
CREATE OBJECT: cnt_c TYPE c1,cnt_1 TYPE c2.
MOVE cnt_c to cnt_2 .
1
CNT_C
1CNT_1
CNT_2
Interface References
You use reference variables to access objects.
As well as reference variables that refer to a class, you can also create then withreference to an interface. These reference variables can contain references toobjects of classes that implement the relevant interface.
The interface allows the user to access all of the interface components
of the object to which the reference points. This means that the usercan access the components that were added to the class definition by theinterface implementation.
When you use interface reference variables, the (static) type of the referencevariable and the (dynamic) type of the object it is pointing to are always different(polymorphism).
8/4/2019 ABAPObjectWorkshopCourseNotes
48/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 48
CLASS bicycle DEFINITION.
PUBLIC SECTION.INTERFACES status. METHODS drive.
PRIVATE SECTION.DATA speed TYPE i.
ENDCLASS.
CLASS bicycle DEFINITION.PUBLIC SECTION.
INTERFACES status. METHODS drive.
PRIVATE SECTION.DATA speed TYPE i.
ENDCLASS.
Interface for Object State - Implementation
CLASS counter DEFINITION.PUBLIC SECTION.
INTERFACES status. METHODS increment.
PRIVATE SECTION.DATA count TYPE i.
ENDCLASS.
CLASS counter DEFINITION.
PUBLIC SECTION.INTERFACES status. METHODS increment.
PRIVATE SECTION.DATA count TYPE i.
ENDCLASS.
CLASS bicycle IMPLEMENTATION.
METHOD status~write. WRITE: 'Speed of bicycle is',
speed.ENDMETHOD. METHOD drive.
speed = speed + 10.ENDMETHOD.
ENDCLASS.
CLASS bicycle IMPLEMENTATION.
METHOD status~write . WRITE: 'Speed of bicycle is',
speed.ENDMETHOD. METHOD drive.
speed = speed + 10.ENDMETHOD.
ENDCLASS.
INTERFACE status. METHODS write.
ENDINTERFACE.
INTERFACE status. METHODS write.
ENDINTERFACE .
CLASS counter IMPLEMENTATION. METHOD status~write. WRITE: 'Count in counter is',
count.ENDMETHOD. METHOD increment.
count = count + 1.ENDMETHOD.
ENDCLASS.
CLASS counter IMPLEMENTATION. METHOD status~write . WRITE: 'Count in counter is',
count.ENDMETHOD. METHOD increment.
count = count + 1.ENDMETHOD.
ENDCLASS.
The interface STATUS writes the state of an object (its attributes) to a list.
It contains the method WRITE to do so.
Two classes implement the interface and its method.
8/4/2019 ABAPObjectWorkshopCourseNotes
49/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 49
Interface for Object State - Use
DATA: count TYPE REF TO counter, bike TYPE REF TO bicycle,status TYPE REF TO status.
CREATE OBJECT: count, bike.
DO 5 TIMES.CALL METHOD: count->increment,
bike->drive.ENDDO.
status = count.CALL METHOD status->write.
status = bike.CALL METHOD status->write.
DATA: count TYPE REF TO counter, bike TYPE REF TO bicycle,status TYPE REF TO status .
CREATE OBJECT: count, bike.
DO 5 TIMES.CALL METHOD: count->increment,
bike->drive.ENDDO.
status = count.CALL METHOD status->write .
status = bike.CALL METHOD status->write .
Counter status
Bike speed
An interface reference is used to address two different objects.
8/4/2019 ABAPObjectWorkshopCourseNotes
50/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 50
Events
Introduction
Overview
Declaring and triggering events
Event handler methods
Handling events
Example: Overflow in counter
8/4/2019 ABAPObjectWorkshopCourseNotes
51/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 51
2
1
1
Events - Introduction
Events are components of classes
Methods can raise the events of their class
Handler methods can be triggered by events
Objects can announce externally that their state has changed by triggering anevent.
Other objects can contain handler methods that are executed when the event istriggered.
In contrast to normal method calls, where the caller has the control and knows thecalled method, an event trigger never knows who will handle the event. This is theprinciple of publish and subscribe, which holds statically for the definition of theevent and its handlers as well as dynamically for raising and handling the event.
A class can declare events statically during its definition and an object can raiseevents during runtime without having to know whether or by whom they are used.
Examples, for where events are frequently used are user interactions on screensor changes of state during workflow.
8/4/2019 ABAPObjectWorkshopCourseNotes
52/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 52
Event trigger
CLASS c1 DEFINITION.PUBLIC SECTION.
EVENTS e1 EXPORTING VALUE(p1)TYPE i.
METHODS m1.
PRIVATE SECTION.DATA a1 TYPE i.
ENDCLASS.
CLASS c1 IMPLEMENTATION. METHOD m1.
a1 = ...
RAISE EVENT e1EXPORTING p1 = a1.
ENDMETHOD.ENDCLASS.
CLASS c2 DEFINITION.PUBLIC SECTION.
METHODS m2 FOR EVENT e1 OF c1IMPORTING p1.
PRIVATE SECTION.DATA a2 TYPE i.
ENDCLASS.
CLASS C2 IMPLEMENTATION. METHOD m2.
a2 = p1....
ENDMETHOD.ENDCLASS.
Event handler
Events - Overview
To be able to trigger an event, a class must declare the event in its declarationpart and raise it in one of its methods..
Events can contain EXPORTING parameters, but since their purpose is only toannounce that the object has changed its state, they cannot have IMPORTINGparameters..
Events are handled by special methods. To handle an event, a method must havebeen declared as a handler method for that event, and must have been registeredfor it at runtime.
In the above example, class C1 has an event E1, which is triggered by the methodM1. Class C2 contains a method M2 that can handle event E1 from class C1.
8/4/2019 ABAPObjectWorkshopCourseNotes
53/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 53
CLASS ... DEFINITION.
... SECTION.
METHODS ...
EVENTS ... [EXPORTING VALUE(...) TYPE ... [OPTIONAL]].
CLASS-EVENTS ...
ENDCLASS.
CLASS ... DEFINITION.
... SECTION.
METHODS ...
EVENTS ... [EXPORTING VALUE(...) TYPE ... [OPTIONAL]].
CLASS-EVENTS ...
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ...
...RAISE EVENT ... EXPORTING ... = ......
ENDMETHOD.
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ...
...RAISE EVENT ... EXPORTING ... = ...
...ENDMETHOD.
ENDCLASS.
Declaring and Triggering Events
You declare events in the declaration part of a class. There are two kinds -instance events and static events.
Events can have EXPORTING parameters. These are always passed by value,and reflect the state of the triggering object.
If a class contains an instance event, it may be triggered by any instance methodof the class. Static events can be triggered by any method of the class. Staticmethods may only trigger static events.
You can trigger an event in a method using the RAISE EVENT statement. You must use the EXPORTING addition of the RAISE EVENT to pass all of the
event parameters that are non-optional.
8/4/2019 ABAPObjectWorkshopCourseNotes
54/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 54
CLASS ... DEFINITION.
... SECTION.
METHODS ... FOR EVENT ... OF ... [IMPORTING ... SENDER ... ].
ENDCLASS.
CLASS ... DEFINITION.
... SECTION.
METHODS ... FOR EVENT ... OF ... [IMPORTING ... SENDER ... ].
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ......
ENDMETHOD.
ENDCLASS.
CLASS ... IMPLEMENTATION.
METHOD ......
ENDMETHOD.
ENDCLASS.
Event Handler Methods
Any class may contain event handler methods for events of other classes.
The interface of an event handler method may only contain formal parameters thathave been defined in the declaration of the corresponding event. The attributes ofthe parameters are also inherited from the event definition. However, the eventhandler method does not have to accept and use all of the parameters passed inthe RAISE EVENT statement.
Events have an implicit parameter called SENDER, which you can accept as anormal IMPORTING parameter. This allows the event handler for an instanceevent to access the triggering instance.
If you declare an event handler method in a class, the instances of the class orthe class itself is then capable of handling the event.
8/4/2019 ABAPObjectWorkshopCourseNotes
55/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 55
PROGRAM ...
DATA: trigger TYPE REF TO trigger,handler_1 TYPE REF TO handler,handler_2 TYPE REF TO handler.
CREATE OBJECT: trigger, handler_1, handler_2.
SET HANDLER handler_1->handle_eventhandler_2->handle_event FOR trigger.
CALL METHOD trigger->raise_event.
PROGRAM ...
DATA: trigger TYPE REF TO trigger,handler_1 TYPE REF TO handler,handler_2 TYPE REF TO handler.
CREATE OBJECT: trigger, handler_1, handler_2.
SET HANDLER handler_1->handle_eventhandler_2->handle_event FOR trigger.
CALL METHOD trigger->raise_event.
Event Handling - Registration
If you want an event handler method to react to an event, you must define atruntime the trigger to which you want it to respond.
The SET HANDLER statement links a list of handler methods to correspondingevent triggers - either instance events or static events.
The syntax and effect of the SET HANDLER statement differs according to theevent type.
With instance events, you must use the FOR addition to specify the triggeringinstance for which you want to register the trigger. You can either specify a singletriggering instance using a reference variable , or specify the handler for allinstances using the statement SET HANDLER FOR ALL INSTANCES.
FOR ALL INSTANCES also applies to triggering instances that do not yet existwhen the registration is made.
You cannot use the FOR addition with static events. Instead, the registrtationapplies automatically to the entire class or all classes that implement an interfacewith a static event.
The SET HANDLER statement also has an addition ACTIVATION, which allowsyou to register and deregister handlers automatically.
8/4/2019 ABAPObjectWorkshopCourseNotes
56/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 56
2
TRIGGERHANDLER_2
HANDLER_1
Ereignis
.
Methode
1
1Methode
Handling Events - References
Unlike methods, where the caller has control of the program, and knows the calledmethod, the trigger of an event does not know which methods, if any, areregistered for it.
For each SET HANDLER statement, the system creates an entry in a handlertable, invisible to the user, for each triggering instance of each event for which ahandler method has been registered.
The handler table contains the names of the handler methods and references tothe registered handling instances. Entries in the table are created by the SETHANDLER statement. A reference to an instance in a handler table counts as ause of the instance, exactly like a reference in a reference variable. Handler tableentries therefore affect the lifetime of objects. In the above illustration, this meansthat the instances 1 and 2 are not deleted by thegarbage collector as long as they are registered for event handling, even if thereference varaibles HANDLER_1 and HANDLER_2 are initialized.
You can delete entries from the handler table using the ACTIVATION addition of
the SET HANDLER statement. If the triggering instance is deleted by the garbagecollector, the entire handler table, including all its references, is deleted.
Static events have a handler table for the class that is not instance-specific.
When an event is triggered, the system searches the corresponding event tableand executes the listed methods in their instances (or classes, in the case of statichandler events).
8/4/2019 ABAPObjectWorkshopCourseNotes
57/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 57
Threshold in Counter - Trigger
CLASS counter DEFINITION.
PUBLIC SECTION. METHODS increment.EVENTS critical_value EXPORTING value(excess) TYPE i.
PRIVATE SECTION.DATA: count TYPE i,
threshold TYPE i VALUE 10.ENDCLASS.
CLASS counter DEFINITION.
PUBLIC SECTION. METHODS increment.EVENTS critical_value EXPORTING value(excess) TYPE i.
PRIVATE SECTION.DATA: count TYPE i,
threshold TYPE i VALUE 10.ENDCLASS.
CLASS counter IMPLEMENTATION. METHOD increment.
DATA diff TYPE i.count = count + 1.
IF count > threshold.
diff = count - threshold.RAISE EVENT critical_value
EXPORTING excess = diff.ENDIF.
ENDMETHOD.
ENDCLASS .
CLASS counter IMPLEMENTATION. METHOD increment.
DATA diff TYPE i.count = count + 1.
IF count > threshold.
diff = count - threshold.RAISE EVENT critical_valueEXPORTING excess = diff.
ENDIF.ENDMETHOD.
ENDCLASS .
The class COUNTER implements a counter.
It triggers the event CRITICAL_VALUE when a threshold is exceeded, and passesthe difference as a parameter.
8/4/2019 ABAPObjectWorkshopCourseNotes
58/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 58
Threshold in Counter - Handling
CLASS handler DEFINITION.PUBLIC SECTION.
METHODS handle_excess FOR EVENT critical_value OFcounter IMPORTING excess.
ENDCLASS.
CLASS handler DEFINITION.PUBLIC SECTION.
METHODS handle_excess FOR EVENT critical_value OFcounter IMPORTING excess.
ENDCLASS.
DATA: cnt TYPE REF TO counter,react TYPE REF TO handler.
CREATE OBJECT: cnt, react.
SET HANDLER react->handle_excess FOR ALL INSTANCES.
DO 20 TIMES.CALL METHOD cnt->increment.
ENDDO.
DATA: cnt TYPE REF TO counter,react TYPE REF TO handler.
CREATE OBJECT: cnt, react.
SET HANDLER react->handle_excess FOR ALL INSTANCES .
DO 20 TIMES.CALL METHOD cnt->increment.
ENDDO.
CLASS handler IMPLEMENTATION. METHOD handle_excess. WRITE: / Excess is', excess.
ENDMETHOD.ENDCLASS.
CLASS handler IMPLEMENTATION. METHOD handle_excess.
WRITE: / Excess is', excess.ENDMETHOD.
ENDCLASS.
The class HANDLER handles the exception in COUNTER.
The handler is registered at runtime using a reference variable that points to theobject.
8/4/2019 ABAPObjectWorkshopCourseNotes
59/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 59
Using Global Classes
Class pools
Class Browser and Class Builder
Class Builder
Example: Us ing CL_GUI_PICTURE
8/4/2019 ABAPObjectWorkshopCourseNotes
60/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 60
TYPES
CLASS
...ENDCLASS.
INTERFACE ...
ENDINTERFACE.
TYPES
CLASS
...ENDCLASS.
INTERFACE ...
ENDINTERFACE.
CLASS DEFINITION PUBLIC....
ENDCLASS.
CLASS DEFINITION PUBLIC....
ENDCLASS.
CLASS IMPLEMENTATION....
ENDCLASS.
CLASS IMPLEMENTATION....
ENDCLASS.
Visibility
CLASS-POOL ...
Class Pools
Globally-defined classes and interfaces are contained within special ABAPprograms called class pools (type K) or interface pools (type J) respectively. Eachclass or interface pool contains the definition of a single global class or interface.The programs are automatically generated when you create a class or interfaceusing the Class Builder.
A class pool is similar to a module pool or function group. It contains declarativeand executable ABAP statements, but cannot be started on its own. The runtime
system can create instances of the class (objects) when requested to do so by theCREATE OBJECT statement. These instances can execute the statements in theclass pool.
Class pools contain a definition part for declarative statements, a declaration partand implementation part for the class, and implementation parts for local classes.
The local classes and interfaces that you define in the definition part of a classpool are not externally visible. They have a similar function to local classes and
interfaces in other ABAP programs. Local classes can only be instantiated inmethods of the global class. Since class pools may not contain subroutines, localclasses are the only way of modularizing the functions of a global class.
8/4/2019 ABAPObjectWorkshopCourseNotes
61/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 61
Class Library and Class Browser
Global transportable classes are administered in the class library .
The class library also allows you to work with local definitions.
The Class Browser provides a hierarchical view of the class library.
You can start the Class Browser from the Class Builder.
Unlike function modules and function groups, the rollout of global transportableclasses is controlled.
Internal quality assurance for the class library at SAP will probably become thetask of the BAPI/BOR group when the BOR is incorporated in the class library.
8/4/2019 ABAPObjectWorkshopCourseNotes
62/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 62
Class Builder
You create global classes and interfaces using the Class Builder .
You define the components of the class or interface on the screen.
The Class Builder then generates the corresponding declarative codingautomatically.
You only have to use the ABAP Editor to implement the methods.
The above illustration is an extract from the methods of the global classCL_GUI_PICTURE. Here you see only the specializations of the subclass, but youcan also choose to display the methods that are inherited from superclasses.
8/4/2019 ABAPObjectWorkshopCourseNotes
63/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 63
CLASS screen_handler DEFINITION.PUBLIC SECTION.
METHODS: handle_node_double_clickFOR EVENT node_double_clickOF cl_gui_simple_treeIMPORTING node_key.
PRIVATE SECTION.DATA: html_viewer TYPE REF TO cl_gui_html_viewer,...
CREATE OBJECT: html_viewer EXPORTING parent = container,...
SET HANDLER event_handler->handle_node_double_click FOR tree....
CLASS screen_handler DEFINITION.PUBLIC SECTION.
METHODS: handle_node_double_clickFOR EVENT node_double_clickOF cl_gui_simple_treeIMPORTING node_key.
PRIVATE SECTION.DATA: html_viewer TYPE REF TO cl_gui_html_viewer ,...
CREATE OBJECT: html_viewer EXPORTING parent = container,...
SET HANDLER event_handler->handle_node_double_click FOR tree....
CLASS screen_handler IMPLEMENTATION. METHOD handle_node_double_click....
CALL METHOD html_viewer->show_url EXPORTING url = url....
ENDMETHOD.ENDCLASS.
CLASS screen_handler IMPLEMENTATION. METHOD handle_node_double_click....
CALL METHOD html_viewer->show_url EXPORTING url = url....
ENDMETHOD.ENDCLASS.
Using Global Classes
Above are extracts from program DEMO_ABAP_OBJECTS_SPLIT_SCREENthat uses global classe from the CFW (Control Framework).
There is a local class SCREEN_HANDLER to handle events fromCL_GUI_SIMPLE_TREE.
There are reference variables that can point to objects of CL_GUI_PICTURE,CL_GUI_SIMPLE_TREE, CL_GUI_HTML_VIEWER ...
For further information about GUI controls, refer to the SAP Control Frameworkdocumentation.
8/4/2019 ABAPObjectWorkshopCourseNotes
64/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 64
CL_GUI_PICTURE and CL_GUI_SIMPLE_TREE
The illustration shows how you can use the classes of the CFW to place variouscontrols on a screen.
8/4/2019 ABAPObjectWorkshopCourseNotes
65/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 65
Mouse Click
A mouse click on a node of the tree
8/4/2019 ABAPObjectWorkshopCourseNotes
66/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 66
CL_GUI_HTML_VIEWER
and an HTMLbrowser appears in another part of the screen.
8/4/2019 ABAPObjectWorkshopCourseNotes
67/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 67
Further Information
Keyword documentation
Example Library
8/4/2019 ABAPObjectWorkshopCourseNotes
68/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 68
KeywordDocumentation
ABAP Keyword Documentation
Further Information
8/4/2019 ABAPObjectWorkshopCourseNotes
69/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 69
Further Information
Example Library
8/4/2019 ABAPObjectWorkshopCourseNotes
70/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 70
Exercises
1. Defining classes
2. Creating objects
3. Deriving classes using inheritance
4. Using interfaces
5. Triggering and handling events
8/4/2019 ABAPObjectWorkshopCourseNotes
71/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 71
Exercises - Scenario
Interface StatusWith methods fordisplayingattributes
Class "Truck"with its own maximumspeed and attribute output
Class "Helicopter"Can handle eventsfrom ship
Class "Ship"with its own maximum speed andattribute output, a name, and an event
Class "Vehicle"with attribute forspeed, and a
method forchanging it
During the exercises, you will write a program in five steps to realize the abovescenario.
8/4/2019 ABAPObjectWorkshopCourseNotes
72/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 72
Exercise 1 - Classes
Copy the template ABAP_OBJECTS_ENJOY_0 into an own program.
Define a local class VEHICLE in the designated area in front of thepredefined class MAIN.
Class VEHICLE should have the protected instance attributes SPEEDand MAX_SPEED for its speed and maximum speed, and the publicmethods SPEED_UP, STOP, and WRITE.
SPEED_UP should have an IMPORTING parameter STEP. Themethod should increase the speed by STEP, but not allow it toexceed the maximum speed.
STOP should reset the speed to zero.
WRITE should display a list line containing the speed and themaximum speed.
ABAP_OBJECTS_ENJOY_0: Template, contains a class MAIN with a staticalmethod START. During program execution, START is called during the systemevent START-OF-SELECTION. You do not need MAIN during exercise 1 yet.
VEHICLE: Class for vehicles
SPEED: Speed. Type integer, starting value 0.
MAX_SPEED: Maximum speed. Type integer, starting value 50. SPEED_UP: Increases SPEED by STEP (type I). If SPEED > MAX_SPEED, set
SPEED to MAX_SPEED.
STOP: Set SPEED to zero.
WRITE: Display the following line: Vehicle speed = SPEED Max. speed =MAX_SPEED.
8/4/2019 ABAPObjectWorkshopCourseNotes
73/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 73
Exercise 2 - Objects
Continuing the program from exercise 1, create objects from theclass VEHICLE.
Program the respective coding in the predefined method START ofclass MAIN.
Define a reference variable VEHICLE with type VEHICLE, and aninternal table VEHICLE_TAB, whose line type is also a referencevariable to this class.
In a DO loop, create a number of instances of the class VEHICLE andinsert them into the internal table.
In a LOOP construction, call the methods SPEED_UP and WRITEonce for each entry in the internal table. When you call SPEED_UP,pass the value SY-TABIX * 10 to the parameter STEP.
START: method of class MAIN, that will contain all data declarations andstatements to create objects and to work with the objects. Encapsulating thefunctions of the program in method START circumvents the declaration ofunnecessary global data.
VEHICLE: Reference variable defined with reference to class VEHICLE.
VEHICLE_TAB: Internal table with line type defined with reference to classVEHICLE.
DO loop: Series of CREATE OBJECT with VEHICLE, appended toVEHICLE_TAB..
LOOP: Read from VEHICLE_TAB to VEHICLE and call the methods SPEED_UPand WRITE.
TABINDEX: Auxiliary variable with type I for calculating the actual parameter forformal parameter STEP in the method SPEED_UP.
8/4/2019 ABAPObjectWorkshopCourseNotes
74/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 74
Exercise 3 - Inheritance
Change your program from exercise 2 to define classes TRUCK and SHIP asdirect subclasses of VEHICLE.
The class TRUCK should have an instance constructor and redefine themethod WRITE.
The class SHIP should have an IMPORTING parameter NAME, a new publicattribute NAME, and should also redefine the method WRITE.
The instance constructor of each class should change the maximum speed.The instance constructor of SHIP should set the attribute NAME to the actualparameter that you imported.
The WRITE method should show the class from which the display comes. ForSHIP, use the NAME attribute.
Declare extra reference variables TRUCK and SHIP for the new classes.
You can delete the code that creates objects for VEHICLE. Instead, create oneinstance of each of your new classes and place the corresponding referenceinto VEHICLE_TAB.
Call the method SPEED_UP for both classes using the correct subclassreference, and WRITE using a superclass reference.
TRUCK: Class for truck CONSTRUCTOR: Set MAX_SPEED to 100
WRITE: Display the following: Truck speed = SPEED Max speed = MAX_SPEED
SHIP: Class for ship NAME, Attribute with type STRING
CONSTRUCTOR: Set MAX_SPEED to 30 and ME->NAME to NAME.
WRITE: Display the following: NAME Speed = SPEED Max speed = MAX_SPEED
TRUCK: Reference variable with reference to class TRUCK
SHIP: Reference variable with reference to class SHIP.
When you create a ship using CREATE OBJECT, pass a name for the ship.
The speeds of the truck and ship should be increased by 30 and 10 respectively.
Use VEHICLE_TAB for the output, as before.
8/4/2019 ABAPObjectWorkshopCourseNotes
75/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 75
Exercise 4 - Interfaces
Change your program from exercise 3 so that the method WRITE is containedin an interface STATUS.
The class VEHICLE should implement the interface instead of its own WRITE
method. The name must be changed accordingly in each implementation(including the subclasses), but the function remains the same.
Replace the reference variables VEHICLE and the table VEHICLE_TAB withthe interface reference STATUS and internal table STATUS_TAB.
Use these references to display the status of the objects.
Create a new class HELICOPTER that also implements STATUS. Declare analias WRITE in that class for the interface method.
The interface method in HELICOPTER should display a different line fromthat displayed in VEHICLE.
Declare a reference variable HELI for the class HELICOPTER, create acorresponding object, and insert the reference variable into the tableSTATUS_TAB.
STATUS: Interface with method WRITE.
VEHICLE: Implements STATUS and its method STATUS~WRITE.
TRUCK, SHIP: Redefine STATUS~WRITE.
HELICOPTER: Implements STATUS and its method STATUS~WRITE.
HELICOPTER: ALIASES WRITE FOR STATUS~WRITE.
STATUS~WRITE in HELICOPTER: Display the following: 'Helicopter' .
STATUS: Reference variable with reference to STATUS.
STATUS_TAB: Internal table with line type reference to STATUS.
8/4/2019 ABAPObjectWorkshopCourseNotes
76/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 76
Exercise 5 - Events
Change your program from exercise 4 to include an event DAMAGEDfor the class SHIP.
Redefine the method SPEED_UP in the class SHIP.
When the maximum speed is exceeded, SPEED_UP should set themaximum speed to zero and trigger the event DAMAGED.
Add a new method RECEIVE to the class HELICOPTER to allow it tohandle the event DAMAGED. Import the implicit parameter SENDER.
RECEIVE should use the SENDER parameter to display the name ofthe ship that triggered the event.
Register the handler method of the object to which HELI is pointing
as a handler for objects from the class SHIP. Increase the speed of the object from the class SHIP until it exceeds
the maximum speed and triggers the event.
SHIP: Declare the event DAMAGED and redefine SPEED_UP.
SPEED_UP in SHIP: If SPEED > MAX_SPEED, set MAX_SPEED to zero, callthe method STOP, and trigger the event DAMAGED.
HELICOPTER: New method RECEIVE as handler for DAMAGED from CL_SHIPwith IMPORTING parameter SENDER.
RECEIVE: Call the alias method WRITE and additionally display the following:'received call from' SENDER->NAME.
Register HELI->RECEIVE for all instances of class SHIP using SET HANDLER.
In a DO loop, increase the speed of the ship in increments of 10 until themaximum speed is exceeded.
8/4/2019 ABAPObjectWorkshopCourseNotes
77/77
SAP AG 2000 F01 TechED Hamburg (Keller) / 77
Copyright 2000 SAP AG (All rights reserved)
Some software products marketed by SAP AG and its distributors contain proprietarysoftware components of other software vendors.
Microsoft , WINDOWS , NT , EXCEL , Word and SQL-Server are registered trademarks ofMicrosoft Corporation.
IBM , DB2 , OS/2 , DB2/6000 , Parallel Sysplex , MVS/ESA , RS/6000, AIX , S/390 ,AS/400 , OS/390 , and OS/400 are registered trademarks of IBM Corporation.
OSF/Motif is a registered trademark of Open Software Foundation.
ORACLE is a registered trademark of ORACLE Corporation, California, USA.
INFORMIX -OnLine for SAP is a registered trademark of Informix Software Incorporated.
UNIX , X/Open , OSF/1 , and Motif are registered trademarks of The Open Group.
ADABAS is a registered trademark of Software AG.
SAP, SAP-Logo, mySAP.com, R/2, R/3, RIVA, ABAP, SAP-EDI, SAP Business Workflow, SAPEarlyWatch, SAP ArchiveLink, ALE/WEB, BAPI, SAPPHIRE, Management Cockpit, SEM, aretrademarks or registered trademarks of SAP AG in Germany and in several other countriesall over the world. All other products mentioned are trademarks or registered trademarks oftheir respective companies.