73
/Document title Object-Oriented Programming ABAP OO Alex Glorie - 2010

Object-Oriented Programming - skynet.beusers.skynet.be/am261047/Boek/ABAP-OO/files/abap-oo.pdf · ABAP Objects 4/73 2 Theoretical part 2.1 Procedural Programming The procedural programming

  • Upload
    dolien

  • View
    245

  • Download
    2

Embed Size (px)

Citation preview

/Document title

Object-Oriented Programming

ABAP OO

Alex Glorie - 2010

ABAP Objects

2/73

Table of contents 1 Introduction ___________________________________________________ 3

2 Theoretical part _______________________________________________ 4

2.1 Procedural Programming ________________________________________ 4 2.1.1 Working with Subroutines _____________________________________________ 5 2.1.2 Working with Function Groups _________________________________________ 6 2.1.3 Working with Includes ________________________________________________ 9 2.1.4 Working with Macros ________________________________________________ 10

2.2 Object-Oriented Programming __________________________________ 11 2.2.1 Advantages ________________________________________________________ 11 2.2.2 Classes ___________________________________________________________ 13

2.2.2.1. Visibility _______________________________________________________ 14 2.2.2.2. Attributes ______________________________________________________ 15 2.2.2.3. Methods ______________________________________________________ 17

2.2.2.3.1. Constructor _________________________________________________ 20 2.2.2.3.2. Class constructor ____________________________________________ 21

2.2.2.4. Working with objects/classes _____________________________________ 22 2.2.3 Generalization ______________________________________________________ 26

2.2.3.1. Inheritance ____________________________________________________ 26 2.2.3.2. Casting _______________________________________________________ 30 2.2.3.3. Polymorphism _________________________________________________ 33 2.2.3.4. Interfaces _____________________________________________________ 35

2.2.4 Events ____________________________________________________________ 37 2.2.5 Summary __________________________________________________________ 41

3 Practical Part_________________________________________________ 44

3.1 Class Builder __________________________________________________ 44

3.2 Some extras for the Class Builder _______________________________ 66 3.2.1 The Attributes Tab __________________________________________________ 66 3.2.2 Typing ____________________________________________________________ 66 3.2.3 Methods Tab _______________________________________________________ 67 3.2.4 Signature __________________________________________________________ 68 3.2.5 Visibility ___________________________________________________________ 68 3.2.6 Functional method __________________________________________________ 68

4 Local Class __________________________________________________ 71

ABAP Objects

3/73

1 Introduction

What is ABAP Objects ?

You are probably reading this manual to obtain a clear answer to this question. We shall try to provide you with the answer :

ABAP Objects is the object-oriented extension of the ABAP programming language of SAP.

A frequently asked question is whether the introduction of ABAP Objects implies that the existing ABAP is now obsolete. This is of course not the case !

More info can be found on : SAP SDN

ABAP Objects

4/73

2 Theoretical part

2.1 Procedural Programming

The procedural programming model is based on the modularization of programs into functional units with local data areas.

ABAP programs are generally modularized through their processing block structure. Each ABAP program requires as a minimum an event block such as START-OF-SELECTION.

On can modularize ABAP programs by using procedures with their own name and data area.

Modularizing a program into procedures = dividing the program into several source code parts which goes beyond the main division into event blocks and dialog modules.

Benefits :

Program readability

Program maintenance

Data encapsulation

In ABAP, the procedural model offers 2 forms of modularization : function modules (= externally) and subroutines (= internally).

Figure 1 - Procedural programming

ABAP Objects

5/73

2.1.1 Working with Subroutines

A subroutine in ABAP is called with FORM and must be ended with ENDFORM.

Figure 2 – Working with subroutines

Figure 3 – Result

You can now start extending the subroutines with adding parameters to it. This is however very important, as it is the only way of using highly generalized algorithms in the subroutine.

You can do this by adding : USING and CHANGING

ABAP Objects

6/73

2.1.2 Working with Function Groups

From a technical viewpoint a function module is a procedure of an ABAP program, just like the subroutine.

What distinguishes function modules from subroutines is how they are managed by the ABAP Workbench. Each function module is a unique repository object which is known to all other ABAP programs.

Function modules are created in function groups. The primary purpose of a function group is to act as the main program for function modules.

Figure 4 - Working with function groups

ABAP Objects

7/73

Definition :

Figure 5 - Definition ZCOUNTER

Figure 6 - Function Z_SET_COUNTER

Figure 7 - Function Z_INCREMENT_COUNTER

Figure 8 - Function Z_GET_COUNTER

ABAP Objects

8/73

Call :

Figure 9 - Report ZCOUNTER (call the functions)

The result = 7

G_count is defined in the top of the function pool.

Figure 10 - General data of the function

What is the disadvantage? I can only create 1 „instance‟ of the function group. So what if I want to use any number of „counters‟? This is not possible with function groups (without additional programming).

Figure 11 - Several counters

ABAP Objects

9/73

2.1.3 Working with Includes

Include programs move parts of the source code of large programs to separate units. These units can be maintained and transported independently !

In general there is an include for the global data of the program, the top include.

To incorporate an include program in another program, use INCLUDE.

Figure 12 - Report with include

Figure 13 - Include

Figure 14 – Result

ABAP Objects

10/73

2.1.4 Working with Macros

If a statement sequence is to be reused several times in a program, this can be programmed once into a macro.

DEFINE macro.

…Statements

END-OF-DEFINITION

The statement of the macro can contain up to 9 placeholders &1…&9.

Figure 15 - Working with macros

Figure 16 - Result

ABAP Objects

11/73

2.2 Object-Oriented Programming

In the real world we can identify a variety of objects which all have characteristics and specific functions. Take your car, for example : it has characteristics such as engaged gear, speed, etc. and functions such as starting, accelerating and braking. In object-orientation we call the characteristics of an object attributes and the functions methods.

Object-oriented programming tries to map the real-world objects with their attributes and functions as realistically as possible in program constructs.

In the object-oriented programming model a different approach is used as in the procedural programming model. Attributes and methods which belongs to a specific object are grouped together (encapsulated) and made accessible to the user through a well-defined interface behind which the implementation details of the objects are hidden. Ideally, the attributes of an object are only changed by the methods of the object and not directly by the user of an object. This ensures that the status of the object is always consistent.

Object orientation focuses on objects that represent either abstract or concrete things in the real world. They are first viewed in terms of their characteristics, which are mapped using the object‟s internal structure and attributes (data). The behavior of an object is described through methods and events (functionality).

Objects form capsules containing the data itself and the behavior of that data. Objects should enable you to draft a software solution that is a one-to-one mapping of the real-life problem area.

2.2.1 Advantages

Abstraction This refers to the ability to reflect the real-world processes as realistically in the programming language as possible. These processes can be business or a technical nature.

Encapsulation Encapsulation means that the implementation of an object is hidden from other components in the system, so that they cannot make assumptions about the internal status of the object and therefore dependencies on specific implementations do not arise.

Polymorphism Polymorphism (ability to have multiple forms) in the context of object technology signifies that objects in different classes have different reactions to the same message.

Inheritance Inheritance defines the implementation relationship between classes, in which one class (the subclass) shares the structure and the behavior defined in one

ABAP Objects

12/73

or more other classes (super classes). Note: ABAP Objects only allows single inheritance.

Others :

Complex software systems become easier to understand, since object-oriented structuring provides a closer representation of reality than other programming techniques.

In a well-designed object-oriented system, it should be possible to implement changes at class level, without having to make alterations at other points in the system. This reduces the overall amount of maintenance required.

Through polymorphism and inheritance, object-oriented programming allows you to reuse individual components.

In an object-oriented system, the amount of work involved in revising and maintaining the system is reduced, since many problems can be detected and corrected in the design phase.

ABAP Objects is not a new language, but has been developed as an extension of

ABAP. It integrates seamlessly into ABAP syntax and the ABAP programming

model. All enhancements are strictly upward compatible.

Object orientation (OO), or to be more precise, object-oriented programming,

is a problem-solving method in which the software solution reflects objects

in the real world.

ABAP Objects

13/73

2.2.2 Classes

Classes form the basis of any object-oriented programming language. A class is the model or template for an object in the same way that a data type is the model for a data object. You can therefore say that a class is an object type. In order to work with objects in a program you must first define classes.

ABAP Objects provides the CLASS and ENDCLASS statements for defining classes in an ABAP program. This is called a local class. Global classes are created with the Class Builder tool of the ABAP Workbench in the Class Library.

Figure 17 – Class

ABAP Objects

14/73

2.2.2.1. Visibility

Figure 18 – Object visibility The object in the above model has two layers: an outer shell and an inner core. Users can only see the outer shell, while the inner core remains hidden (the internal status of an object can only be seen within the object itself). Public components (outer shell): the outer shell contains the components of the object that are visible to users, such as attributes (data), methods (functions) and events. All users have direct access to these components. The public components of an object form its external point of contact. Private components (inner core): the components of the inner core (attributes, methods and events) are only visible within the object itself. The attributes of an object are generally private. These private attributes of an object can only be accessed using the methods of that object itself. Why are the private components of an object “hidden”? : This principle is called “information hiding” or “encapsulation” and is used to protect the user. Let us assume that an object changes its private components, while its external point of contact remains unchanged. Any user who simply needs to access the object‟s external point of contact can carry on working with the object as usual. The user does not notice the change. However, if an object changes its public components, then any user who accesses these public components must take these changes into account.

Protected components : The components of this section are protected and can be addressed by the methods of the subclass (heirs) and the methods of the class itself.

ABAP Objects

15/73

Every object has an identity, a status (quantity of attributes) and behavior (quantity

of methods and events). The structure and behavior of similar objects are defined

in a class which they share.

Identity is a characteristic that differentiates each object from all other objects.

Identity is often confused with having the same attribute values or with a unique

name. Two different objects can have identical attribute values and still not be

identical.

Example: two coffee cups are the same height and diameter, have the same

handle and are both white. Although they look exactly the same, they are still two

separate cups.

The way to handle objects is by using classes !

Figure 19 – Class

2.2.2.2. Attributes

Attributes are the data objects within a class. They reflect the object‟s state.

Attributes of the airplane class are, for example:

­ Name

­ Seats

­ Weight

­ Length

­ Wings

­ Tank

ABAP Objects

16/73

Figure 20 - Attributes and visibility

As a general rule, you should define as few public attributes as possible.

Figure 21 - instance vs. static attributes

There are two kinds of attributes

­ Static attributes

­ Instance attributes

Instance attributes are attributes that exist separately for each object.

Instance attributes are defined using the DATA keyword.

ABAP Objects

17/73

Static attributes exist once only for each class and are visible for all (runtime)

instances in that class. Static attributes usually contain information that is common

to all instances, such as:

­ Data that is the same in all instances

­ Administrative information about the instances in that class (for example,

counters and so on)

­ Static attributes are defined using the CLASS-DATA keyword.

Figure 22 – Example

The attribute count was set as a static attribute. The attributes name and weight as instance attributes.

When we have 2 instances of the object, the attribute count is the same for both the objects.

2.2.2.3. Methods

Methods are internal procedures in classes that determine the behavior of an object. They can access all attributes in their class and can therefore change the state of an object.

The way in which objects behave is implemented in the methods of class !

Methods have a parameter interface that enables them to receive values when

they are called and pass values back to the calling program.

ABAP Objects

18/73

Figure 23 – Methods

In ABAP Objects, methods can have IMPORTING, EXPORTING, CHANGING and

RETURNING parameters as well as EXCEPTIONS. All parameters can be passed

by value or reference.

You can define a return code for methods using RETURNING. You can only do this

for a single parameter, which additionally must be passed as a value. Also, you

cannot then define EXPORTING and CHANGING parameters. You can define

functional methods using the RETURNING parameter (explained in more detail

below).

All input parameters (IMPORTING, CHANGING parameters) can be defined as

optional parameters in the declaration using the OPTIONAL or DEFAULT

additions. These parameters then do not necessarily have to be passed when the

object is called. If you use the OPTIONAL addition, the parameter remains

initialized according to type, whereas the DEFAULT addition allows you to enter a

start value.

As with attributes, methods can be private or public.

ABAP Objects

19/73

Figure 24 - Public vs. private methods

Static methods are defined on the class level. They are similar to instance

methods, but with the restriction that they can only use static components (such as

static attributes) in the implementation part. This means that static methods do not

need instances and can therefore be called from anywhere. They are defined using

the CLASS-METHODS statement, and they are bound by the same syntax and

parameter rules as instance methods.

ABAP Objects

20/73

Figure 25 - Instance methods

2.2.2.3.1. Constructor

The constructor is a special (instance) method in a class and is always named

CONSTRUCTOR. The following rules apply:

Each class has exactly one constructor.

The constructor does not need to be defined if no implementation is defined.

The constructor is automatically called during runtime within the CREATE OBJECT statement.

If you need to implement the constructor, then you must define and implement it in the PUBLIC SECTION.

Another method called CLASS_CONSTRUCTOR is called the first time a class is accessed.

ABAP Objects

21/73

Figure 26 – Constructor

2.2.2.3.2. Class constructor

The static constructor is a special constructor and always named CLASS_CONSTRUCTOR.

It is executed exactly once per program/class. The static constructor of a class is called automatically before the class is first accessed, that is, before any of the following actions are executed :

Creating an instance of the class with CREATE OBJECT

Addressing a static attribute with <class name>=><attribute>

Calling a static method with CALL METHOD <class name>=><method>

Registering a static event with SET HANDLER <class name>=><method> FOR <object>

Figure 27 - Static Constructor

ABAP Objects

22/73

2.2.2.4. Working with objects/classes

A class contains the generic description of an object. It describes all the characteristics that are common to all the objects in that class. During the program runtime, the class is used to create specific objects (instances). This process is called instantiation.

Objects are instantiated using the statement: CREATE OBJECT. During instantiation, the runtime environment dynamically requests main memory space and assigns it to the object.

ABAP Objects

23/73

Figure 28 – Reference

In the example we have the class lcl_airplane. To reference (= use) that class we use the TYPE REF TO.

This acts as a pointer to an object.

To actually create the object and to have an instance, we use the CREATE OBJECT.

Figure 29 – Instance

As soon as no more references point to an object, the Garbage Collector removes

it from the memory.

The Garbage Collector is a system routine that automatically deletes objects that

can no longer be addressed from the main memory and releases the memory

space they occupied.

ABAP Objects

24/73

How to access attributes of an object in a program ?

Figure 30 - Access attributes

Static attributes are accessed using <class name>=><class_attribute>.

Instance attributes are accessed using <instance>-><instance_attribute>.

How to access/call methods of an object ?

Figure 31 - Access methods

ABAP Objects

25/73

Instance methods: using CALL METHOD <reference>-><instance_method>.

Static methods: using CALL METHOD <class name>=><class_method>.

ABAP Objects

26/73

2.2.3 Generalization

Some extra features of a class are :

inheritance

cast

polymorphism

interfaces

2.2.3.1. Inheritance

Inheritance is a relationship in which one class (the subclass) inherits all the main characteristics of another class (the super class). The subclass can also add new components (attributes, methods, and so on) and replace inherited methods with its own implementations.

Inheritance should be used to implement generalization and specialization relationships. A super class is a generalization of its subclasses. The subclass in turn is a specialization of its super classes.

ABAP Objects only has single inheritance !

Figure 32 – Inheritance

If inheritance is used properly, it provides a significantly better structure, as common components only need to be stored once centrally (in the super class) and are then automatically available to subclasses. Subclasses also profit immediately from changes (although the changes can also render them invalid!).

ABAP Objects

27/73

Figure 33 – Inheritance and visibility

Inheritance provides an extension of the visibility concept: there are protected components. The visibility of these components lies between that of the public components (visible to all users, all subclasses, and the class itself), and private (visible only to the class itself). Protected components are visible to and can be used by all subclasses and the class itself.

Subclasses cannot access the private components (particularly attributes) of the super class. Private components are genuinely private. This is particularly important if a (super) class needs to make local enhancements to handle errors: it can use private components to do this without knowing or invalidating subclasses.

In ABAP Objects, you must keep to the section sequence PUBLIC, PROTECTED, PRIVATE.

ABAP Objects

28/73

Figure 34 - Inheritance and constructor

The constructor of the super class must be called within the constructor of the subclass. The reason for this is the special task of the constructor: to ensure that objects are initialized correctly. Only the class itself, however, can initialize its own (private) components correctly; this task cannot be carried out by the subclass. Therefore it is essential that all (instance) constructors are called in an inheritance hierarchy (in the correct sequence).

For static constructors, unlike instance constructors, the static constructor in the super class is called automatically, that is, the runtime system automatically ensures that, before the static constructor in a particular class is executed, the static constructors of all its super classes have already been executed.

ABAP Objects

29/73

Figure 35 - Inheritance and redefining methods

The REDEFINITION statement for the inherited method must be in the same SECTION as the definition of the original method. (It can therefore not be in the PRIVATE SECTION, since a class‟s private methods are not visible and therefore not re definable in subclasses!).

If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method. The reason for this is that ABAP Objects does not support overlaying.

In ABAP Objects you can call the method from the super class using the pseudo-reference super: CALL METHOD super->method_name.The pseudo-reference

super can only be used in redefined methods.

ABAP Objects

30/73

2.2.3.2. Casting

Instances from subclasses can be used in any context in which the instances to the super class appear.

Figure 36 – Casting

One of the significant principles of inheritance is that an instance from a subclass can be used in every context in which an instance from the super class appears. This is possible because the subclass has inherited all components from the super class and therefore has the same interface as the super class. The user can therefore address the subclass instance in the same way as the super class instance.

Variables of the type “reference to super class” can also refer to subclass instances at runtime.

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 view with more detail to a view with less detail.

What is a narrowing cast used for? A user who is not interested in the finer points of cargo or passenger planes (but only, for example, in the tank gauge) does not need to know about them. This user only needs to work with (references to) the lcl_airplane class. However, in order to allow the user to work with cargo or passenger planes, you would normally need a narrowing cast.

ABAP Objects

31/73

Figure 37 - Narrow cast

After the narrowing cast you can use the airplane reference to access the

components of the cargo plane instance that were inherited from lcl_airplane, obviously in some cases with the limitations entailed by their visibility. You can no longer access the cargo-plane-specific part of the instance (cargo in the above example) using the airplane reference.

Figure 38 - Widening casting

ABAP Objects

32/73

The type of case described above is known as a widening cast because it changes the view to one with more details. The instance assigned (a cargo plane in the above example) must correspond to the object reference (cargo_airplane in the above example), that is, the instance must have the details implied by the reference.

This is also known as a “down cast”.

The widening cast in this case does not cause an error because the reference airplane actually points to an instance in the subclass lcl_cargo_airplane. The dynamic type is therefore „REF TO lcl_cargo_airplane‟.

Figure 39 - Widening cast – errors

Here the widening cast produces the MOVE_CAST_ERROR runtime error that can be caught with “CATCH ... ENDCATCH”, because the airplane reference does not point to an instance in the subclass lcl_cargo_airplane, but to a “general airplane object”. Its dynamic type is therefore „REF TO lcl_airplane‟ and does not

correspond to the reference type cargo_airplane.

Use the :

CATCH SYSTEM-EXCEPTION MOVE_CAST_ERROR = 4.

Cargo_airplane ?= airplane.

ENDCATCH.

IF SY-SUBRC EQ 4. => you catched the error

ABAP Objects

33/73

2.2.3.3. Polymorphism

When objects from different classes react differently to the same method call, this is known as polymorphism. To do this, the classes implement the same method in different ways. This can done using inheritance, by redefining a method from the super class in subclasses and implementing it differently. Interfaces are also introduced below: they too can enable polymorphic behavior!

When an instance receives a message to execute a particular method, then that method is executed if it has been implemented by the class the instance belongs to. If the class has not implemented that method, but only inherited and not redefined it, then a search up through the inheritance hierarchy is carried out until an implementation of that method is found.

Polymorphism is one of the main strengths of inheritance: the user can work in the same way with different classes, regardless of their implementation. The search for the right implementation of a method is carried out by the runtime system, not the user!

Figure 40 – Polymorphism

Objects from different classes (lcl_cargo_airplane and lcl_passenger_airplane in the above example ) can be stored in an internal table consisting of references to

the super class (lcl_airplane in the above example, and then processed identically

(polymorphically).

ABAP Objects

34/73

Figure 41 - Polymorphism

What coding is actually executed when estimate_fuel_consumption is called

depends on the dynamic type of the plane reference variable, that is, it depends

on which object from which (sub)class plane points to.

You can use polymorphism to write programs that are generic to a high degree and that do not even need to be changed if use cases are added. In the simple example above, this means that, should a further subclass be added, for example, for airplanes that fly in space, the above coding would not need to be changed.

ABAP Objects

35/73

2.2.3.4. Interfaces

Figure 42 – Interfaces

In ABAP Objects, interfaces are implemented in addition to and independently of classes. Interfaces exclusively describe the external point of contact of a class, but they do not contain their own implementation part.

Interfaces are usually defined by a user. The user describes in the interface which services (technical and semantic) it needs in order to carry out a task. The user never actually knows the providers, but communicates with them through the interface. In this way the user is protected from actual implementations and can work in the same way with different classes/objects, as long as they provide the services required (this is polymorphism using interfaces).

The above example shows two users: the document library and the file browser. Both define the tasks that potential providers must be able to carry out: display and print in the first case and show a node for the file folder display in the second. Various providers (plain text files, spreadsheets) can perform all the services required, but one provider (the folder) can only perform the service required by the File Browser and can therefore not be used by the Document Library.

ABAP Objects

36/73

Figure 43 - Defining interface

In ABAP Objects, the same components (attributes, methods, constants, types, alias names) can be defined in an interface in largely the same way as in classes. However, interfaces do not have component visibility sections.

Interfaces are implemented in classes.

The interface name is listed in the definition part of the class. Interfaces can only be implemented „publicly‟ and are therefore always in the PUBLIC SECTION (this is only valid as of Release 4.6). If you do not do this, you risk multiple implementations, if a super class and a subclass both implement the same interface privately.

The operations defined in the interface are implemented as methods of a class. A check is carried out to ensure that all the methods defined in the interfaces are actually present in the implementation part of the class (for global interfaces, a missing or superfluous implementation of an interface method results in a ToDo warning).

The 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 carrying out the implementation by prefixing the interface name, followed by a tilde (the Interface Resolution Operator): <interface name>~<component name>.

ABAP Objects

37/73

2.2.4 Events

Figure 44 – Events

By triggering an event, an object or a class announces a change of state, or that a certain state has been achieved.

In the above example, the airplane class triggers the event „touched_down‟. Other classes subscribe to this event and process it. The air-traffic controller marks the plane as landed on the list, the pilot breathes a sigh of relief and the passenger, Mr. Miller, applauds.

Events link objects or classes more loosely than direct method calls do. Method calls establish precisely when and in which statement sequence the method is called. However, with events, the reaction of the object to the event is determined by the triggering of the event itself.

Events are most often used in GUI implementations.

ABAP Objects

38/73

Figure 45 - Defining events

Both instance and static events can be triggered in instance methods.

Only static events can be triggered in static methods.

Events can only have EXPORTING parameters which must be passed by value.

Triggering an event using the statement RAISE EVENT has the following effect:

The program flow is interrupted at that point.

The event handler methods registered to this event are called and processed.

Once all event handler methods have been executed, the program flow starts again.

ABAP Objects

39/73

Figure 46 - Handling events

Event handler methods are triggered by events (RAISE EVENT), although they can also be called like normal methods (CALL METHOD).

The interface of the event handler method consists solely of IMPORTING parameters. Only parameters from the definition of the corresponding event (event interface) can be used. An event interface only has EXPORTING parameters and is defined using the EVENTS statement in the declaration of the event. The parameters are typed in the event definition and the typing is passed to the event handler method, that is, the interface parameters of the event handler method cannot be typed in the definition of the event handler method.

ABAP Objects

40/73

Figure 47 - Registering an event

When an event is triggered, only those event handler methods that have registered themselves using SET HANDLER by this point at runtime are executed.

You can register an event using Activation „X„ (see above example), and deregister it using Activation „SPACE„ (see next slide). You can also register and deregister using a variable <var>, which is filled with one of these two values. If you do not specify a value for Activation, then the event is registered (default setting).

You can register several methods in one SET-HANDLER statement:

SET HANDLER <ref_handle1>-><handler_method1>

<ref_handler>-><handler_methodN>

FOR <ref_sender> | FOR ALL INSTANCES.

ABAP Objects

41/73

2.2.5 Summary

Figure 48 - Classes/Encapsulation

Figure 49 - Polymorphism/Inheritance

ABAP Objects

42/73

Figure 50 – Strengths

ABAP Objects

43/73

ABAP Objects

44/73

3 Practical Part

3.1 Class Builder

Transaction code = SE24 or SE80 (general overview)

Run transaction SE24, and enter the name of the class. The naming convention is ZCL_*

Figure 51 - Class Builder - create

Press the „Create‟ button.

ABAP Objects

45/73

Fill in the popup-screen :

Figure 52 - Popup-screen

Choose :

instantiation = Public (=> any one can use it, and see it)

Uncheck Final (=> final class can not have subclasses !)

Now we are on the main screen of the Class Builder :

Figure 53 - Main screen Class Builder

ABAP Objects

46/73

Let‟s create some Public methods :

constructor

speed_up

stop

show

Click on the tab „Methods‟ :

Type in „constructor‟ in the method name + press ENTER. You automatically see the „constructor‟-sign.

Figure 54 - Constructor

Now fill in the other methods…

Figure 55 - Methods

For the method speed_up we will fill in the parameters. Put the cursor on the method speed_up and click on the button „Parameters‟.

Figure 56 - Methods parameters

ABAP Objects

47/73

Now we will fill in the attributes.

Figure 57 - Attributes

If you want a specific type (types : begin of…), click on the yellow arrow. There are 2 attributes as protected. This means you can re-use them in sub classes. There are 2 attributes as private. This means no one can see them ! One attributes is a static attribute => this means if you have several instances of the class, this attribute stays the same for all the instances !

Now let‟s add some code to the methods.

Double click on a method.

Figure 58 - Method implementation

ABAP Objects

48/73

And all the code :

Click on the button „Signature‟ to see the parameters !

Figure 59 - Method speed_up

Figure 60 - Method stop

Figure 61 - Method show

ABAP Objects

49/73

Now we can test the class by clicking on the „Test‟ button

Figure 62 - Test the class

Figure 63 - The class for testing

Click on the execute button next to speed_up :

Figure 64 - Parameters for speed_up

You need to fill in the speed in the import parameter im_step, and click on execute. You‟ll return to the main screen. Now press on the execute button next to Show.

You will see the popup with the message :

Vehicle = 1 => this comes from the constructor

Speed = 15 => this comes from the import parameter for method speed_up.

ABAP Objects

50/73

Figure 65 - Method show

Now let‟s create a small program to test the class.

Figure 66 - Program to test the class

ABAP Objects

51/73

Figure 67 - Vehicle 1

Figure 68 - Vehicle 2

Figure 69 - Vehicle 10

As you can see, each time the code passes the CREATE OBJECT the method constructor is called, and the static variable object_count is added by 1 ! Once the Speed is more than 50, the speed remains the same !

Now let us create a sub class ZCL_TRUCK_01 of class ZCL_VEHICLE_01.

Figure 70 - Class ZCL_TRUCK_01

ABAP Objects

52/73

Click on the button „Create inheritance‟ :

Figure 71 - Class ZCL_TRUCK_01 and super class

The methods from the super class are inherited (copied) :

Figure 72 - Methods are inherited

ABAP Objects

53/73

Enter the truck‟s own constructor by double-clicking on it, and change the code as follows :

Figure 73 - Constructor sub class

As the constructor already exists in the super class, we must first call the constructor of the super class, and then implement the own code ! This can be done by the statement super->

Now we will redefine the method show.

Figure 74 – Redefine

Figure 75 - Redefine method show

ABAP Objects

54/73

We will not call the method show in the super class => comment out the super->show.

Let us now create a subclass ZCL_SHIP_01 => you should know how to do this…

Add a new attribute :

Figure 76 - Attribute

Let‟s change the constructor => add a parameter

Figure 77 - Parameter for constructor

The parameter im_name is automatically an import parameter, because the constructor can only have importing parameters !

Figure 78 – constructor

ABAP Objects

55/73

Also change the method show

Figure 79 - Method show

We used the statement me-> to specify that the variable name is coming from this object (the current instance)… You can also just write name, but the see the different with the own objects variables and the super class variables, use the statement me->.

We‟ll now change our test program…

Figure 80 - Test program

This program is a good example of polymorphism ! See why ??? We call method show for object vehicle. But vehicle can be a truck or a ship !!!

ABAP Objects

56/73

Let‟s create an interface.

Figure 81 - Create interface

Create 1 method without parameters :

Figure 82 - Interface method show

We will now implement this interface in the vehicle class. Do not forget to delete the method show we use in this class => it will be replaced by the interface !

Figure 83 - Add interface to class

This will add the method of the interface to our class :

Figure 84 - Method of interface

ABAP Objects

57/73

Implement the following code :

Figure 85 - Implementation interface method

And delete the method SHOW from the class !!!

Now create a public alias for the interface :

Figure 86 - Alias

Why ? Because otherwise you‟ll need to call the method with ZIF_STATUS_01~SHOW, and now you just can call SHOW => this means that we don‟t need to change the code of our test program !

Let‟s check the Truck class:

Figure 87 - Inheritance : interface

As you can see : the interface was automatically copied (= inheritance).

ABAP Objects

58/73

Figure 88 - Inheritance : method

And also the method of the interface is inherited.

The same is true for the ship class.

Let‟s now create a helicopter class that also implements the same interface !

And implement the following code for the method SHOW

Figure 89 – Implementation

We will now change the test program :

ABAP Objects

59/73

Figure 90 - Test program Interfaces

Notice that we link the object status to the interface !!!

Why can we not use this :

Figure 91 - link to the class ?

Because the heli class is NOT a subclass of the vehicle class ! But is has the same interface as the other classes.

ABAP Objects

60/73

We will now add an EVENT to the ship class.

If the speed > max speed of the ship => we should raise an event !

Figure 92 – Event

Redefine the method speed_up

Figure 93 - Redefine method

Figure 94 - Implementation

ABAP Objects

61/73

We still need a handler to capture the event ! We will do this in the helicopter class.

Figure 95 - Event handler method

Add the default import parameter SENDER

Figure 96 - Add parameter

Add the following code :

Figure 97 - Implementation of event handler

ABAP Objects

62/73

Let‟s change the test program :

Figure 98 - Test event

Figure 99 - Result event handler

ABAP Objects

63/73

We will now define an exception class. Whenever there is a problem in a method we will raise an exception (instead of raising an event). This will give us an error message, or just tell the program that something went wrong. We can capture this via the statement TRY…ENDTRY.

We will add this in the vehicle class.

Select the method SPEED_UP and click on the „Exceptions‟ button

Figure 100 – Exceptions

Figure 101 - Exception class

ABAP Objects

64/73

The exception class is automatically created:

Figure 102 - Exception class

Change the implementation of method SPEED_UP

Figure 103 - Add RAISE EXCEPTION

ABAP Objects

65/73

Let‟s change the test program to capture this exception.

Figure 104 - Test exception class

Figure 105 - Exception!

When the loop (DO) reaches the 4-th time, the speed > max_speed => raise the exception… this will go to the statement CATCH.

ABAP Objects

66/73

3.2 Some extras for the Class Builder

3.2.1 The Attributes Tab

Set initial values

Read only flag : constant is most of the time a better choice

Figure 106 - Attributes Tab

3.2.2 Typing

Figure 107 – Typing

More complex types can be created manually ! by clicking on the

Figure 108 - Typing manually

ABAP Objects

67/73

3.2.3 Methods Tab

Figure 109 - Methods

Figure 110 - Parameters for Methods

Figure 111 - Type of Parameters

ABAP Objects

68/73

3.2.4 Signature

Tip : use the signature button to see the parameters in the code of the method !

Figure 112 – Signature

3.2.5 Visibility

Figure 113 – Visibility

Public : any other program can adjust the attributes

Private : only the class itself can adjust the attributes

Protected : the attributes can be disposed to other objects (can be used by inheritance)

3.2.6 Functional method

We call a method functional when there is only 1 returning parameter !

Figure 114 - Functional method

ABAP Objects

69/73

Normally one would do :

O_flight->get_flight_details(importing r_sflight = l_sflight).

But with a functional method, one can immediately put the value to a variable !

L_sflight = o_flight->get_flight_details( ).

ABAP Objects

70/73

ABAP Objects

71/73

4 Local Class

One can also create a class in a program.

Why ? Generally we create a class with the Class Builder if somebody else can use the same class, or the same methods.

If you only need a class for a one time purpose, you should create the class locally into a program.

The best way to do it, is create a program which is used for the code. Then create an include for the class.

This gives a better overview when using SE80.

Figure 115 - Local class in program

Figure 116 - Include => local class

ABAP Objects

72/73

It is possible that you create a program with a local class and methods, and that somebody else also wants to use a method you use.

In this case, you can create a global class from an local class.

Let‟s create a global class from the example above.

Go to the Class Builder

Figure 117 - Class Builder

Figure 118 - Local class Vehicle

ABAP Objects

73/73

You‟ll need to change the global name to a Z-name !!! and then select the line !!!

Figure 119 - Import the local class

Now click on the import button…

Figure 120 - Global class from local class