1 of 243

ABAP 100

Object-Oriented Programming with SAP NetWeaver

1

© msg systems ag, 15.01.2013

2 of 243

ABAP Programming

2

© msg systems ag, 15.01.2013

Level 3

ABAP Dictionary

ABAP030 2 Days

Development of user dialogs

ABAP110 2 Days

Level 1

​

ABAP Workbench

basics and

concepts

ABAP 010 3 Days

Level 1

Basics of

SAP Web AS

SAP Basics ½ Day

ABAP Objects

Object Oriented

Programming

with SAP NetWeaver

ABAP 100 3 Days

Table Controls &�ALV Grids

ABAP111 1 ½ Days

3 of 243

Agenda

  1. Objectives and Introduction
  2. Introduction to Object-Oriented Programming
  3. Analysis and Design
  4. Fundamentals of Object-Oriented Programming
  5. Inheritance
  6. Casting
  7. Interfaces
  8. Events
  9. Global Classes and Interfaces
  10. Programming Techniques
  11. Exception Handling
  12. Dynamic Programming

3

© msg systems ag, 15.01.2013

4 of 243

1. Objectives and Introduction

4

© msg systems ag, 15.01.2013

5 of 243

1. Objectives and Introduction�ABAP Objects – Level 3

5

© msg systems ag, 15.01.2013

​

  • A new Concept in application programming, which started imposing itself around the middle of ‘90
  • With the introduction of the Release 4.6 the SAP changed the name of the language from ABAP/4 in ABAP Objects

​

Advanced Business Application Programming

for

Object-Oriented Programming

ABAP Objects

6 of 243

1. Objectives and Introduction�Course Objectives

6

© msg systems ag, 15.01.2013

This course provides knowledge to:

  • the concepts of object-oriented programming
  • the development of Business Applications using ABAP Objects

​

​

​

7 of 243

1. Objectives and Introduction�Course Learning Objectives

7

© msg systems ag, 15.01.2013

You will acquire knowledge to:

  • describe and apply the most important concepts:
    • classes / inheritance / interfaces
    • polymorphism with inheritance and interfaces
    • Events
    • Exception handling
  • write programs using ABAP Objects.

​

8 of 243

1. Objectives and Introduction�Overview

8

© msg systems ag, 15.01.2013

????

A travel agency maintains business connections to business partners

​

      • Airlines
      • Rental companies
      • Hotels

9 of 243

2. Introduction to Object-Oriented Programming

  • Procedural Programming
  • Object-Oriented Programming
  • Goals of the Programming Language ABAP Objects

​

9

© msg systems ag, 15.01.2013

10 of 243

2. Introduction to Object-Oriented Programming –�History of Selected Programming Languages

10

© msg systems ag, 15.01.2013

1950

1952

1954

1956

1958

1960

1962

1964

1966

1968

1970

1972

1974

1976

1978

1980

1982

1984

1986

1988

1990

1992

1994

1995

1996

1997

1998

Machine language

Assembler

C++

ABAP Objects

ABAP

Java

Fortran

LISP

Cobol

APL

APL2

Algol 60

Basic

Prolog

Logo

Simula 67

Algol 68

PL1

BCPL

Pascal

Smalltalk

Smalltalk-80

FP1

Ada

Modula-2

C

Object Pascal

Modula-3

Miranda

Eiffel

Eiffel-3

Oberon

Oberon-2

Ada-95

11 of 243

2. Introduction to Object-Oriented Programming

  • Procedural Programming
  • Object-Oriented Programming
  • Goals of the Programming Language ABAP Objects

11

© msg systems ag, 15.01.2013

12 of 243

2. Introduction – Procedural Programming�Characteristics of Procedural Programming

12

© msg systems ag, 15.01.2013

  • Separation of data and functions
  • Direct access to data is possible

Daten

Daten

Daten

Daten

Daten

Funktion

Funktion

Funktion

Funktion

Funktion

Funktion

Funktion

Funktion

13 of 243

2. Introduction – Procedural Programming�Typical Procedural ABAP Program

13

© msg systems ag, 15.01.2013

REPORT zabap_demo

* -----------------

​

TYPES: ...

​

DATA: ...

​

...

​

PERFORM f1 ...

​

CALL FUNCTION ...

​

...

​

* -----------------

FORM f1 ...

...

ENDFORM.

  • Data declarations

​

​

  • Main program
    • Subroutine calls
    • Function module calls

​

  • Definition of subroutines

14 of 243

2. Introduction – Procedural Programming�Encapsulating Data Using Function Groups

14

© msg systems ag, 15.01.2013

Main program Function groups

Global data objects

Function group 1

Global data

Function module 1

Function group 2

Global data

Function module 2

Function module ...

Function module 1

Function module 2

Subroutines

Interface

Interface

15 of 243

2. Introduction – Procedural Programming�Example: Function Group Counter – Definition

15

© msg systems ag, 15.01.2013

FUNCTION-POOL counter.

​

DATA: count TYPE I.

​

FUNCTION SET_COUNTER.

* Local interface IMPORTING VALUE(set_value)

count = set_value

ENDFUNCTION.

​

FUNCTION INCREMENT_COUNTER.

ADD 1 TO count.

ENDFUNCTION.

​

FUNCTION GET_COUNTER.

* Local interface EXPORTING VALUE(get_value)

get_value = count.

ENDFUNCTION.

16 of 243

2. Introduction – Procedural Programming�Example: Function Group Counter – Usage

16

© msg systems ag, 15.01.2013

DATA: number TYPE I VALUE 3.

​

​

CALL FUNCTION 'SET_COUNTER'

EXPORTING set_value = number.

​

DO 4 TIMES.

CALL FUNCTION 'INCREMENT_COUNTER'.

ENDDO.

​

​

CALL FUNCTION 'GET_COUNTER'

IMPORTING get_value = number.

​

WRITE: ..., number, ...

17 of 243

2. Introduction – Procedural Programming�Several Counters

17

© msg systems ag, 15.01.2013

Function group COUNTER

SET_COUNTER

INCREMENT_COUNTER

GET_COUNTER

COUNTER

1 counter any number of counters

  • Not possible with function groups, without additional effort!

18 of 243

2. Introduction – Procedural Programming�Instantiation in object-oriented languages

18

© msg systems ag, 15.01.2013

Several instances�(Objects)�of the same Blueprint�(Type or better Class)�are a fundamental property of object-oriented languages.

ABAP Program with Data

External Session

Internal session of an ABAP program

n. Instance, Class 1

Schnitt-

stelle

Datea

1. Instance, Class 1

Interface

Data

n. Instance, Class m

Schnitt-

stelle

Datea

1. Instance, Class m

Interface

Data

19 of 243

2. Introduction to Object-Oriented Programming

  • Procedural Programming
  • Object-Oriented Programming
  • Goals of the Programming Language ABAP Objects

19

© msg systems ag, 15.01.2013

20 of 243

2. Introduction – Object-Oriented Programming

20

© msg systems ag, 15.01.2013

Kran

Real world

Data and functions

Daten

    Functions

   Functions   

Functions     

Daten

     Functions

   Functions   

Functions     

Daten

     Functions

   Functions   

Functions     

Encapsulation of data and functions

Data

Data

Data

Data

Data

Functions

Functions

Functions

Functions

Functions

Functions

Functions

Functions

21 of 243

2. Introduction – Object-Oriented Programming�Characteristics of the Object-Oriented approach

21

© msg systems ag, 15.01.2013

  • Objects are a direct abstraction of the real world.
  • Processes can be implemented realistically.
  • Objects are units made up of data and the functions belonging to that data.
  • Improved software structure and consistency in the development process.
  • Reduced maintenance effort.
  • Integration of the customer/user into the analysis, design, and maintenance process.

Kran

Real world

22 of 243

2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model

22

© msg systems ag, 15.01.2013

  • Encapsulation of data and functions (Hiding the implementation details)

Data

Functions

  Functions

  • Inheritance
  • Polymorphism for support of generic programming
  • Event controlling

Father

Child 1

Child 2

Code 3

Code 2

display_data

Code 1

Code 4

23 of 243

2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model

23

© msg systems ag, 15.01.2013

  • Encapsulation of data and functions�

​

myNumber

doCall

beCalled

register

Telephone

Telephone

myNumber

register

doCall

beCalled

24 of 243

2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model

24

© msg systems ag, 15.01.2013

    • Inheritance�

​

CellPhone

mySMS

sendSMS

getSMS

Telephone

myNumber

register

doCall

beCalled

OfficePhone

myContacts

addContact

callContact

deleteContact

25 of 243

2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model

25

© msg systems ag, 15.01.2013

beCalled

beCalled

beCalled

MP3

  • Polymorphism for support of generic programming�

​

26 of 243

2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model

26

© msg systems ag, 15.01.2013

  • Event controlling�

​

register_me

msg

Phone

Center

27 of 243

2. Introduction – Object-Oriented Programming�Client/server behavior

27

© msg systems ag, 15.01.2013

  • Objects behave towards each other just liker client/server systems.
  • Every object can essentially fulfill either role.
  • Responsibilities must be specified between the objects.

CALL METHOD server->do_it

Server

Data

Methods

do_it

Data

Methods

call_it

Client

28 of 243

2. Introduction – Object-Oriented Programming�Compatibility and design goals

28

© msg systems ag, 15.01.2013

Compatibility:

  • ABAP Objects is a compatible extension of ABAP
  • ABAP Objects statements can be used in procedural ABAP programs
  • Objects (classes) contain, among other, classical ABAP statements

Design goals:

  • As simple as possible
  • only object-oriented concepts that have proved useful
  • Increased use of type checks

* ABAP Objects Program

​

​

DATA: counter TYPE i,

wa TYPE kna1.

...

​

CLASS lcl_car DEFINITION.

...

ENDCLASS.

​

*--- main program ---------

​

CREATE OBJECT ...

​

counter = counter + 1.

MOVE wa TO ...

​

CLASS lcl_car DEFINITION.

...

ENDCLASS.

CREATE OBJECT ...

29 of 243

2. Introduction – Object-Oriented Programming�ABAP Main Memory and Encapsulation

29

© msg systems ag, 15.01.2013

Internal session

Internal session

Global data objects

Global data objects

Data

Functions

  • Data and business logic are encapsulated in objects

Modularization units

Data

Functions

  • Modularization units for encapsulating functions
  • Working with global data of the main program

30 of 243

2. Introduction – Object-Oriented Programming�The Software Development Process

30

© msg systems ag, 15.01.2013

Test

Implementation

(ABAP Objects)

Requirement,

Idea

Analysis and

Design

Iteration

Mentioned in the course!

31 of 243

2. Introduction – Object-Oriented Programming�Summary

31

© msg systems ag, 15.01.2013

​

You should now be able to:

  • explain the differences between procedural and object-oriented programming models
  • explain the goals of the programming language ABAP Objects

32 of 243

3. Analysis and Design

  • Classification of Objects
  • UML – the Modeling Standard
  • Class diagrams
  • Sequence diagrams

32

© msg systems ag, 15.01.2013

33 of 243

3. Analysis and Design – Classification�Class creation / modeling

33

© msg systems ag, 15.01.2013

lcl_people

lcl_vehicle

Excerpt of the real world

34 of 243

3. Analysis and Design – Classification�Classes as Abstraction Forms

34

© msg systems ag, 15.01.2013

Scrap-merchant

Weight�weight

Make�make

Model� model

PS

HP

Doors�doors

Wheels�wheels

Scrap value�scrapvalue

Color�color

Configuration�configuration

Price�price

Car enthusiast

lcl_vehicle

- make

- ...

- weight

- scrapvalue

lcl_vehicle

- set

- ...

- price

- configuration

35 of 243

3. Analysis and Design – Classification�Classes and Objects

35

© msg systems ag, 15.01.2013

lcl_vehicle

​

…

​

​

…

or

or

Class:

    • General description of object (blueprint)
    • Specifies status data (attributes) and behavior (methods)

Object (Instance):

    • Representation of section of the real world
    • Concrete instance of a class

lcl_vehicle

​

(5) lcl_vehicle

​

​

​

​

36 of 243

3. Analysis and Design

  • Classification of Objects
  • UML – the Modeling Standard
  • Class diagrams
  • Sequence diagrams

36

© msg systems ag, 15.01.2013

37 of 243

3. Analysis and Design – Modeling in UML

37

© msg systems ag, 15.01.2013

  • UML stands for Unified Modeling Language
  • is a worldwide standard
  • it is a language used for the specification, construction,

visualization, and documentation of models for software systems

​

Diagram types:

      • Class diagrams
      • Behavior diagrams, e.g. the Sequence diagram
      • Component diagrams
      • Deployment diagrams
      • ...

38 of 243

3. Analysis and Design – Classification�Class diagram in UML notation

38

© msg systems ag, 15.01.2013

Attributes

(Properties)

Methods

(Functions)

lcl_vehicle

make

model

.....

price

color

​

set_make()

display_attributes()

increases_speed()

…

Assoziationsme

Optional,

does not have to be specified

Events + Handlers

brake

accelerate

Class name

39 of 243

3. Analysis and Design – Modeling in UML�Example of a Class Diagram

39

© msg systems ag, 15.01.2013

lcl_car

lcl_rental

lcl_vehicle

lcl_bus

lcl_customer

1

0..*

0..*

1

1

1..*

1..*

1

lcl_wheel

lcl_truck

lcl_booking

40 of 243

3. Analysis and Design – Modeling in UML�Association

40

© msg systems ag, 15.01.2013

A customer can rent any amount of cars

Description of the association

Common cardinalities

* or 0..* any amount

1 exactly one

1..* at least one

0..1 no more than one

1

0..*

lcl_booking

lcl_customer

A booking refers to a single customer

◀books

41 of 243

3. Analysis and Design – Modelling with UML�Aggregation und Composition

41

© msg systems ag, 15.01.2013

Aggregation is a special�case of association,�a whole-part relationship.

Composition is a special�case of aggregation, an�existence-dependent�a whole-part relationship.

Composition Symbol

Aggregation Symbol

lcl_vehicle

lcl_booking

1..*

1..1

lcl_vehicle

lcl_wheel

1..1

0..*

42 of 243

3. Analysis and Design – Modelling with UML�Generalization and Specialization

42

© msg systems ag, 15.01.2013

or

Generalization

Specialization

Generalization

Specialization

lcl_truck

lcl_vehicle

lcl_car

lcl_vehicle

lcl_truck

lcl_car

Arrow for Inheritance

43 of 243

3. Analysis and Design – Modelling with UML�Sequence diagram: Example

43

© msg systems ag, 15.01.2013

Lifeline

of the object

Control focus

Return value

Create Object

Time

Process description

(optional)

Object :Class

Object :Class

1:Method(parameter)

44 of 243

3. Analysis and Design – Modelling with UML�Sequence diagram : Delegation

44

© msg systems ag, 15.01.2013

re_level = � fuel / fuel_max * 100.

re_level = � tank->get_fuel_level( ).

1: get_fuel_level( )

2: get_fuel_level( )

re_level

re_level

:lcl_car

:lcl_driver

:lcl_tank

45 of 243

3. Analysis and Design – Summary

45

© msg systems ag, 15.01.2013

​

You should now be able to

  • name the most important diagram types in UML
  • create class diagrams
  • create sequence diagrams

46 of 243

Exercise

46

© msg systems ag, 15.01.2013

Exercise

Analysis and Design

UML Class Diagrams

MIN

HOURS

47 of 243

4. Fundamentals of Object-Oriented Programming

  • Classes, Attributes and Methods
  • Objects, Instances of Classes
  • Visibility / Encapsulation
  • Constructor
  • Other fundamental elements

​

47

© msg systems ag, 15.01.2013

48 of 243

4. Fundamentals of Object Oriented Programming�Example of a Class

48

© msg systems ag, 15.01.2013

Public access:

  • Methods
  • Events

Private Access:

  • Data types
  • Attributes

lcl_vehicle

Private

components

Methods:

Implementation

make

model

Public

components

set_make()

get_make()

49 of 243

4. Fundamentals of Object Oriented Programming�Defining Classes

49

© msg systems ag, 15.01.2013

CLASS lcl_periode DEFINITION.

​

​

ENDCLASS.

CLASS lcl_periode IMPLEMENTATION.

​

​

ENDCLASS.

ABAP-Coding

lcl_vehicle

Private

Components

Method

Implementation

Public

Components

50 of 243

4. Fundamentals of Object Oriented Programming�Attributes

50

© msg systems ag, 15.01.2013

(5) lcl_car

Private

make TYPE STRING,

...�� �r_motor � TYPE REF TO ...

Public

(5) lcl_rental

r_car

  • Attribute can have�any data type:
    • C, N, I, P, ..., STRING
    • dictionary types
    • self defined types
    • TYPE REF TO �defines a reference �to an object, here r_car

51 of 243

4. Fundamentals of Object Oriented Programming�Attributes, Types and Constants: Syntax

51

© msg systems ag, 15.01.2013

CLASS <Class_name> DEFINITION.

...

​

TYPES: <normal type_definition>.

​

CONSTANTS: mc_constant TYPE <Type> VALUE <Value>.

​

DATA: mv_var1 TYPE <Type>,

ms_var2 TYPE <DDIC-Type>,

mv_var3 LIKE mv_var1,

mv_var4 TYPE <Type> VALUE <value>,

mv_var5 TYPE <Type> READ-ONLY,

mo_var6 TYPE REF TO <Class>,

mo_var7 TYPE REF TO <Interface>.

​

CLASS-DATA: mv_only_once TYPE ... .

​

ENDCLASS.

TYPES:

CONSTANTS:

DATA:

CLASS-DATA:

52 of 243

4. Fundamentals of Object Oriented Programming�Attributes and Visibility

52

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

​

PUBLIC SECTION.

...

​

PRIVATE SECTION.

DATA: make TYPE string.

ENDCLASS.

CLASS lcl_vehicle DEFINITION.

​

PUBLIC SECTION.

DATA: make TYPE string.

PRIVATE SECTION.

ENDCLASS.

  • Public attributes
    • generally visible �and changeable
    • direct access

​

  • Private attributes
    • only visible and changeable within the class
    • no direct access from outside

PUBLIC SECTION.

PRIVATE SECTION.

53 of 243

4. Fundamentals of Object Oriented Programming�Accessing Private Attributes

53

© msg systems ag, 15.01.2013

r_vehicle

Client

(5) lcl_vehicle

Private

make

Public

set_make()

get_make()

…

54 of 243

4. Fundamentals of Object Oriented Programming�Instance attributes and static attributes

54

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

​

PUBLIC SECTION.

...

PRIVATE SECTION.

DATA: make TYPE string,

...

​

CLASS-DATA: n_o_vehicles TYPE i.

​

ENDCLASS.

​

  • Instance attributes
    • exist per instance
    • Defined with DATA

​

​

  • Static attributes
    • exist per class
    • Defined with CLASS-DATA
    • are also defined as class attributes

CLASS-DATA: n_o_vehicles TYPE i.

DATA: make TYPE string,

55 of 243

4. Fundamentals of Object Oriented Programming�Instance attributes and static attributes

55

© msg systems ag, 15.01.2013

Global data objects

Internal session

(2) lcl_vehicle

n_o_vehicles

Static attribute

(3) lcl_vehicle

​

...

3

r_vehicle1

r_vehicle3

r_vehicle2

(1) lcl_vehicle

...

Static attributes

exist only once

Instances /

objects

56 of 243

4. Fundamentals of Object Oriented Programming�Methods: Syntax

56

© msg systems ag, 15.01.2013

CLASS <Class_name> IMPLEMENTATION.

METHOD <Method_name>.

...

ENDMETHOD.

ENDCLASS.

CLASS <Class_name> DEFINITION.

...

METHODS:

<Method_name>

IMPORTING <im_par> TYPE <Type>

EXPORTING <ex_par> TYPE <Type>

CHANGING <ch_ar> TYPE <Type>

RETURNING value(<re_par>) TYPE <Type>

EXCEPTIONS <Exceptions (not class based)>� RAISING <class based exceptions>.

ENDCLASS.

Methods can

have a signature

The method implementation governs the ‚behavior‘ of the objects .

METHODS:

METHOD

ENDMETHOD.

57 of 243

4. Fundamentals of Object Oriented Programming�Accessing Private Methods

57

© msg systems ag, 15.01.2013

(5) lcl_vehicle

Private

make

...

init_make()

Public

...

set_make()

r_vehicle

Client

58 of 243

4. Fundamentals of Object Oriented Programming�Methods and Visibility

58

© msg systems ag, 15.01.2013

  • Public methods
    • can generally be called

​

  • Private methods
    • can only be called within the class

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS: set_make

IMPORTING im_make TYPE string.

PRIVATE SECTION.

METHODS: init_make.

DATA: make TYPE string.

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.

METHOD init_make.

make = 'No make'.

ENDMETHOD.

METHOD set_make.

IF im_make IS INITIAL.

init_make( )

ELSE.

make = im_make.

ENDIF.

ENDMETHOD.

ENDCLASS.

init_make( )

PUBLIC SECTION.

PRIVATE SECTION.

59 of 243

4. Fundamentals of Object Oriented Programming�Instance methods and static methods

59

© msg systems ag, 15.01.2013

  • Instance methods
    • access to static but also instance components is possible in their implementation
    • can be invoked through an instance
  • Static method
    • can use only static components in their implementation
    • are addressed with their class name

Rules

60 of 243

4. Fundamentals of Object Oriented Programming�Instance- and static methods: Example

60

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

​

PUBLIC SECTION.

METHODS: set_make IMPORTING im_make TYPE string.

CLASS-METHODS: get_count EXPORTING ex_count TYPE i.

​

PRIVATE SECTION.

DATA: make TYPE.

CLASS-DATA: n_o_count TYPE i.

​

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.

...

METHOD get_count.

ex_count = n_o_count.

ENDMETHOD.

​

ENDCLASS.

CLASS-METHODS:

METHOD

ENDMETHOD.

61 of 243

4. Fundamentals of Object Oriented Programming�Summary and UML Notation

61

© msg systems ag, 15.01.2013

lcl_vehicle

- make:string

- model:string

- n_o_vehicles:i

…

+ set_make(im_make:string)

- init_make()

+ get_count():i

…

+ indicates public components

- indicates private components

_ static components are underlined

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS: set_make IMPORTING im_make TYPE string.

CLASS-METHODS: get_count EXPORTING ex_count TYPE i.

​

PRIVATE SECTION.

DATA: make TYPE.

CLASS-DATA: n_o_count TYPE i.

ENDCLASS.

62 of 243

Exercise

62

© msg systems ag, 15.01.2013

Exercise

OOP Fundamentals

Creating a class

MIN

HOURS

63 of 243

4. Fundamentals of Object-Oriented Programming

  • Classes, Attributes and Methods
  • Objects, Instances of Classes
  • Visibility / Encapsulation
  • The Constructor
  • Other fundamental elements

​

63

© msg systems ag, 15.01.2013

64 of 243

4. Fundamentals of Object-Oriented Programming�Creating objects

64

© msg systems ag, 15.01.2013

  • Objects are created with the statement�CREATE OBJECT.
  • They can only be created and addressed using reference variables�

(5) lcl_vehicle

Private

make�modell�ser_no�...

Public

set_make

get_count

…

CREATE OBJECT r_vehicle

r_vehicle

Rules

lcl_vehicle

​

- make

- model

- ser_no

- n_o_vehicles …

​

+ set_make()

- init_make()

+ get_count()

…

65 of 243

4. Fundamentals of Object-Oriented Programming�Definition of Reference Variables

65

© msg systems ag, 15.01.2013

...

​

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

...

PRIVATE SECTION.

...

ENDCLASS.

​

​

CLASS lcl_vehicle IMPLEMENTATION.

...

ENDCLASS.

​

​

DATA: r_vehicle1 TYPE REF TO lcl_vehicle,

r_vehicle2 TYPE REF TO lcl_vehicle.

​

​

START-OF_SELECTION.

...

r_vehicle1

r_vehicle2

?

?

What do these

reference variables

point to?

TYPE REF TO

TYPE REF TO

DATA:

66 of 243

4. Fundamentals of Object-Oriented Programming�Creating Objects

66

© msg systems ag, 15.01.2013

DATA: r_vehicle1 TYPE REF TO lcl_vehicle,

r_vehicle2 TYPE REF TO lcl_vehicle.

​

START-OF-SELECTION.

​

CREATE OBJECT r_vehicle1.

CREATE OBJECT r_vehicle2.

r_vehicle1

r_vehicle2

(4) lcl_vehicle

Private

Public

(3) lcl_vehicle

Private

Public

CREATE OBJECT

CREATE OBJECT

START-OF-SELECTION.

67 of 243

4. Fundamentals of Object-Oriented Programming�Garbage Collector

67

© msg systems ag, 15.01.2013

DATA: r_vehicle1 TYPE REF TO lcl_vehicle,

r_vehicle2 TYPE REF TO lcl_vehicle.

​

START-OF-SELECTION.

​

CREATE OBJECT r_vehicle1.

CREATE OBJECT r_vehicle2.

​

r_vehicle2 = r_vehicle2.

r_vehicle2

(4) lcl_vehicle

Private

Public

(3) lcl_vehicle

Private

Public

r_vehicle2 = r_vehicle2.

r_vehicle1

68 of 243

4. Fundamentals of Object-Oriented Programming�Garbage Collector: Approach

68

© msg systems ag, 15.01.2013

  • All independent references from the global memory are checked. The references point to 'living' objects, that are marked internally.
  • The references from class- and instance attributes to further objects are tracked. These objects are also marked.
  • Unmarked objects are removed from the main memory.

(5) lcl_object

​

CLEAR r_object

(4) lcl_object

​

(2) lcl_object

​

69 of 243

4. Fundamentals of Object-Oriented Programming�Reference Buffering

69

© msg systems ag, 15.01.2013

DATA: r_vehicle TYPE REF TO lcl_vehicle,

itab TYPE TABLE OF REF TO lcl_vehicle.

​

CREATE OBJECT r_vehicle.

APPEND r_vehicle TO itab.

CREATE OBJECT r_vehicle.

APPEND r_vehicle TO itab.

LOOP AT itab INTO r_vehicle.� " work with the current instance �ENDLOOP.

...

​

(2) lcl_object

​

(3) lcl_object

​

APPEND r_vehicle TO itab.

APPEND r_vehicle TO itab.

LOOP AT itab INTO r_vehicle.

ENDLOOP.

70 of 243

4. Fundamentals of Object-Oriented Programming�Aggregation Example

70

© msg systems ag, 15.01.2013

(2) lcl_wheel

​

(3) lcl_wheel

​

(4) lcl_wheel

​

(5) lcl_wheel

​

(5) lcl_vehicle

Private

Public

itab_wheels

71 of 243

Exercise

71

© msg systems ag, 15.01.2013

Exercise

OOP Fundamentals

Object instantiation

MIN

HOURS

72 of 243

4. Fundamentals of Object-Oriented Programming

  • Classes, Attributes and Methods
  • Objects, Instances of Classes
  • Visibility / Encapsulation
  • The Constructor
  • Other fundamental elements

72

© msg systems ag, 15.01.2013

73 of 243

4. Fundamentals of Object-Oriented Programming�Calling Methods

73

© msg systems ag, 15.01.2013

r_vehicle

(5) lcl_vehicle

Private

Public

motor_on()

r_vehicle->motor_on( )

Client

Reference

Object component selector

Method

74 of 243

4. Fundamentals of Object-Oriented Programming�EXPORTING and IMPORTING

74

© msg systems ag, 15.01.2013

Main program

Method

IMPORTING

im_distance

​

​

​

ex_fuel

EXPORTING

When creating a method:

Received values 🡺 IMPORTING

Returned values 🡺 EXPORTING

75 of 243

4. Fundamentals of Object-Oriented Programming�EXPORTING and IMPORTING

75

© msg systems ag, 15.01.2013

Main program

EXPORTING

CALL METHOD …

EXPORTING

im_distance = 500

IMPORTING

ex_fuel = lv_fuel.

IMPORTING

Method

IMPORTING

im_distance

​

​

​

ex_fuel

EXPORTING

When creating a method:

EXPORTING in the IMPORTING parameter

IMPORTING in the EXPORTING parameter

76 of 243

4. Fundamentals of Object-Oriented Programming�Calling Instance Methods: Syntax

76

© msg systems ag, 15.01.2013

Instance methods:

​

​

​

​

​

​

Shorter syntax:

(see online documentation)

CALL METHOD <InstRef>-><InstMethod>

EXPORTING <InpParam> = <Value>

IMPORTING <ExpParam> = <Variable>

CHANGING <ChgParam> = <Variable>

RECEIVING <ReturnVal> = <Variable>

EXCEPTIONS <Exception> = <Nr>.

​

<InstRef>-><InstMethod>( <Parameter> )

DATA: r_vehicle TYPE REF TO lcl_vehicle.

DATA: make_name TYPE string.

...

make_name = `the make of the car`.

​

CALL METHOD r_vehicle->set_make EXPORTING im_make = make_name.�* as of NW 6.1 keyword EXPORTING can be left out

r_vehicle->set_make( make_name )

* now getting something back from method...

r_vehicle->get_make( IMPORTING ex_make = make_name ).

CALL METHOD

->

r_vehicle->set_make

r_vehicle->get_make

->

SPACE!

No space before opening bracket

77 of 243

4. Fundamentals of Object-Oriented Programming�Calling Static Methods: Syntax

77

© msg systems ag, 15.01.2013

CALL METHOD <KlassenName>=><KlassenMethode>(

[Parameter] )

​

<KlassenName>=><KlassenMethode>( [Parameter] )

DATA: r_vehicle TYPE REF TO lcl_vehicle.

DATA: make_name TYPE string,

count TYPE i.

​

...

* get_count has one interface-parameter re_count

CALL METHOD lcl_vehicle=>get_count( IMPORTING re_count = count ).�

* other variant, since 6.1 available, see documentation

lcl_vehicle=>get_count( IMPORTING re_count = count ).

CALL METHOD

=>

=>

lcl_vehicle=>get_count

lcl_vehicle=>get_count

Static methods:

​

​

​

​

​

78 of 243

4. Fundamentals of Object-Oriented Programming�Functional Methods

78

© msg systems ag, 15.01.2013

a = b +

  • Definition:
    • Precisely one RETURNING parameter
    • Otherwise, only IMPORTING parameters and exceptions are possible
  • Call:
    1. RECEIVING-Parameter, or ...
    2. ... implicit calls possible in various expressions:
      • MOVE, CASE, LOOP
      • logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT)
      • arithmetic and bit expressions (COMPUTE)�see example a = b + c

Functional Method

Example

79 of 243

4. Fundamentals of Object-Oriented Programming�Functional Methods: Example

79

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS: get_average_fuel� IMPORTING im_distance TYPE s_distance,

im_fuel TYPE ty_fuel � RETURNING value(re_fuel) TYPE ty_fuel,

ENDCLASS.

DATA: r_vehicle1 TYPE REF TO lcl_vehicle, � r_vehicle2 TYPE REF TO lcl_vehicle,

avg_fuel TYPE ty_fuel.

​

...�* example for short syntax in aritmeth. operation

avg_fuel =

r_vehicle1->get_average_fuel( im_distance = 500 im_fuel = 50 )� + r_vehicle2->get_average_fuel( im_distance = 600 im_fuel = 60 ).

​

​

RETURNING value(

)

80 of 243

4. Fundamentals of Object-Oriented Programming�Non-class-based exceptions: Example

80

© msg systems ag, 15.01.2013

CLASS lcl_plane DEFINITION.

PUBLIC SECTION.

METHODS: get_tank_capacity� RETURNING value(rv_tankcap) TYPE saplane-tankcap

EXCEPTIONS unknown_tank_capacity.

PRIVATE SECTION.

DATA: mv_planetype TYPE saplane-planetype.

ENDCLASS.

DATA: lo_plane TYPE REF TO lcl_plane, � lv_tankcap TYPE saplane-tankcap.

​

* usage of non-class-based exceptions

lo_plane->get_tank_capacity( RECEIVING rv_tankcap = lv_tankcap

EXCEPTIONS unknown_tank_capacity = 1

OTHERS = 2 ).

IF sy-subrc EQ 0.

"Normal operation.

ELSE.

"Exception handling.

ENDIF.

​

EXCEPTIONS unknown_tank_capacity

EXCEPTIONS unknown_tank_capacity = 1

OTHERS = 2

RAISE unknown_tank_capacity.

81 of 243

4. Fundamentals of Object Oriented Programming�External Access to Public Attributes

81

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

DATA: make TYPE string READ-ONLY. "just a demo

CLASS-DATA: n_o_vehicles TYPE i READ-ONLY. "just a demo

...

ENDCLASS.

...

​

DATA: r_vehicle TYPE REF TO lcl_vehicle.

DATA: make_name TYPE string,

count TYPE i.

​

START-OF-SELECTION.

*---------------------------------------

* main program, think of a client !

CREATE OBJECT r_vehicle.

​

make_name = r_vehicle->make. "only if public attr.�count = lcl_vehicle=>n_o_vehicles. "only if public attr.

(2) lcl_vehicle

​

make�...

r_vehicle

r_vehicle->make

lcl_vehicle=>n_o_vehicles

82 of 243

Exercise

82

© msg systems ag, 15.01.2013

Exercise

Fundamentals of OOP

Method Calls

MIN

HOURS

83 of 243

4. Fundamentals of Object Oriented Programming

  • Classes, Attributes and Methods
  • Objects, Instances of Classes
  • Visibility / Encapsulation
  • Constructor
  • Other fundamental elements

​

83

© msg systems ag, 15.01.2013

84 of 243

4. Fundamentals of Object Oriented Programming�Constructor

84

© msg systems ag, 15.01.2013

lcl_vehicle

- make

- model

- n_o_vehicles

…

+ constructor()

…

  • Special method for creating objects with a defined initial state
  • Can only have IMPORTING parameter and EXCEPTIONS
  • In each class there exists one defined constructor�(explicit or implicit)
  • Will be invoked only once per instance

CREATE OBJECT

METHODS:

constructor

IMPORTING <InpParam>� EXCEPTIONS <Exception>� RAISING <class-based exceptions>.

constructor

(3) lcl_vehicle

​

Private

Public

85 of 243

4. Fundamentals of Object Oriented Programming�Constructor: Example

85

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS constructor IMPORTING im_make TYPE string

im_modell TYPE string.

PRIVATE SECTION.

DATA: make TYPE string, weight TYPE p.

CLASS-DATA n_o_vehicles TYPE i.

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.

METHOD constructor.

make = im_make.

modell = im_modell.

ADD 1 TO n_o_vehicles.

ENDMETHOD.

ENDCLASS.

DATA r_vehicle TYPE REF TO lcl_vehicles.

...

CREATE OBJECT r_vehicle� EXPORTING im_make = 'Ferrari'

im_modell = 'F40'.

Automatic call of constructor

Call from the main program

constructor

constructor

CREATE OBJECT

86 of 243

4. Fundamentals of Object Oriented Programming�Overview: Static Constructor

86

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

CLASS-METHODS: class_constructor.

PRIVATE SECTION.

CLASS-DATA: n_o_vehicles TYPE I.

ENDCLASS.

  • Special static method
  • Call when the class is accessed for the first time during that program run
  • Will be called only once per program

CLASS lcl_vehicle IMPLEMENTATION.

METHOD class_constructor.

...

ENDMETHOD. ...

ENDCLASS.

CREATE OBJECT r_vehicle.

​

counter = lcl_vehicle=>n_o_vehicles. "if attribute is public

�lcl_vehicle=>get_count( IMPORTING re_count = counter ).

class_constructor

Implicit constructor call BEFORE

actual processing

CREATE OBJECT r_vehicle

counter = lcl_vehicle=>

lcl_vehicle=>get_count(

class_constructor

IMPORTING re_count = counter ).

n_o_vehicles. "if attribute is public

.

87 of 243

Exercise

87

© msg systems ag, 15.01.2013

Exercise

Fundamentals of OOP

Constructor

MIN

HOURS

88 of 243

4. Fundamentals of Object Oriented Programming

  • Classes, Attributes and Methods
  • Objects, Instances of Classes
  • Visibility / Encapsulation
  • Constructor
  • Other fundamental elements

​

88

© msg systems ag, 15.01.2013

89 of 243

4. Fundamentals of Object Oriented Programming�Namespace inside a class

89

© msg systems ag, 15.01.2013

  • Same namespace for
    • attributes
    • methods
    • events
    • types
    • constants
    • ALIAS names

​

  • Inside the body of methods there exists a local namespace.

​

lcl_vehicle

Private

components

Attribute

make

Method

implementation

Public

components

​

Method

make

STOP

90 of 243

4. Fundamentals of Object Oriented Programming �The Reference Variable me

90

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS constructor

IMPORTING im_make TYPE string

im_modell TYPE string.

PRIVATE SECTION.

DATA make TYPE string. ...

ENDCLASS.

​

lcl_vehicle

Private

components

Attribute

mv_make

Method

implementation

​

me->make

Public

components

CLASS lcl_vehicle IMPLEMENTATION.

METHOD constructor.

DATA make TYPE string VALUE 'Benz'.

CONCATENATE im_make make

INTO me->make.

ENDMETHOD.

​

METHOD meth.

" inside class prefix 'me->' is not

" necessary for calling methods.

display_attributes( ).

ENDMETHOD.

ENDCLASS.

me->make

me->mv_make

91 of 243

4. Fundamentals of Object Oriented Programming �Summary

91

© msg systems ag, 15.01.2013

​

You should now be able to

  • define classes
  • generate objects
  • call methods
  • explain the function of the Garbage Collector

​

​

92 of 243

Exercise

92

© msg systems ag, 15.01.2013

Exercise

Fundamentals of OOP

Calling a private method

MIN

HOURS

93 of 243

5. Inheritance

  • Generalization / Specialization of classes

93

© msg systems ag, 15.01.2013

94 of 243

5. Inheritance�UML Example

94

© msg systems ag, 15.01.2013

„is a“

relationship

lcl_vehicle

- make

- model

- ser_no

- color

- n_o_vehicles …

+ constructor()

+ display_attributes()

+ get_count()

lcl_car

- car_type

- max_seats

- acceleration

+ …

+ get_type()

​

lcl_truck

- max_cargo

- n_o_tanks

- n_o_wheels

+ …

+ get_cargo()

lcl_bus

- max_passengers

- lavatory

- television

+ …

+ get_passengers()

95 of 243

5. Inheritance�Multiple Inheritance?

95

© msg systems ag, 15.01.2013

Specialization

Generalization

no

multiple inheritance!

lcl_super1

lcl_super2

lcl_sub1

lcl_sub2

lcl_sub3

STOP

96 of 243

5. Inheritance�Relationships between Super- and Subclasses

96

© msg systems ag, 15.01.2013

  • Common components are available only �once in superclass
    • New components in superclass are available�automatically in subclass
    • Scope of the new coding is reduced�(“Programming by Difference”)��
  • Subclasses strongly coupled �to superclasses
    • “White Box Reuse”: �Subclass must have detailed knowledge of the implementation in its superclass.

lcl_super

lcl_sub

new�components

Inherited�components

97 of 243

5. Inheritance�Syntax

97

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS: estimate_fuel

IMPORTING im_distance TYPE s_distance � RETURNING value(re_fuel) TYPE ty_fuel.

PRIVATE SECTION.

DATA: make TYPE string,

...

ENDCLASS.

CLASS lcl_truck DEFINITION

INHERITING FROM lcl_vehicle.

PUBLIC SECTION.

METHODS: get_cargo RETURNING VALUE(re_cargo) TYPE ty_cargo.

PRIVATE SECTION.

DATA: max_cargo TYPE ty_cargo.

...

ENDCLASS.

INHERITING FROM

98 of 243

5. Inheritance�Redefining Methods

98

© msg systems ag, 15.01.2013

CLASS lcl_truck IMPLEMENTATION.

METHOD estimate_fuel.

...

super->estimate_fuel(...) �

ENDMETHOD.

ENDCLASS.

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS: estimate_fuel

IMPORTING im_distance TYPE ty_distance � RETURNING value(re_fuel) TYPE ty_fuel.

ENDCLASS.

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.

PUBLIC SECTION.

METHODS estimate_fuel REDEFINITION.� ...

ENDCLASS.

REDEFINITION

super

Signature must be retained!

New implementation of the inherited method

Refers to the superclass component

estimate_fuel

STOP

99 of 243

5. Inheritance�Inheritance and Redefinition of the constructor

99

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS: constructor IMPORTING

im_make TYPE string.

ENDCLASS.

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.

PUBLIC SECTION.

METHODS: constructor IMPORTING im_make TYPE string

im_cargo TYPE ty_cargo.

PRIVATE SECTION.

DATA: max_cargo TYPE ty_cargo.

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.

METHOD constructor.

make = im_make.

ENDMETHOD.

ENDCLASS.

CLASS lcl_truck IMPLEMENTATION.

METHOD constructor.

CALL METHOD super->constructor( im_make = im_make ).

max_cargo = im_cargo.

ENDMETHOD.

ENDCLASS.

Signature may be changed!

Call constructor of immediate superclass!

super->constructor

im_make TYPE string

im_make TYPE string

im_cargo TYPE ty_cargo

100 of 243

5. Inheritance�Rules for Calling the Constructor

100

© msg systems ag, 15.01.2013

DATA: r_2 TYPE REF TO lcl_2,

r_3 TYPE REF TO lcl_3.�

CREATE OBJECT r_2 EXPORTING im_1 = 100.

​

CREATE OBJECT r_3 EXPORTING im_1 = 100

im_2 = 1000.

​

Case 1�Class of instance to be created has constructor

    • supply its parameters.

​

Case 2 �Class of instance to be created has no constructor

    • Search in the inheritance tree for the next highest superclass with a constructor and�supply its parameters.

lcl_1

a1:I

constructor( im_1:i )

lcl_3

a2:I

constructor( im_1:i� im_2:i )

lcl_2

has

has no

101 of 243

5. Inheritance�Inheritance and Visibility

101

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

​

PUBLIC SECTION. ...�

PROTECTED SECTION.� DATA tank TYPE REF TO lcl_tank.

PRIVATE SECTION.

DATA make TYPE string.

​

ENDCLASS.

  • Public components
    • generally visible
    • direct access
  • Protected components
    • visible within the class and within all subclasses
  • Private components
    • only visible within the class
    • no access from outside or from the subclasses

PROTECTED SECTION

lcl_vehicle

- make

- model

# tank

…

+ constructor()

+ display_attributes()

+ get_count()

…

+ public

# protected

- private

static

# tank

102 of 243

5. Inheritance�Visibility of Protected Components

102

© msg systems ag, 15.01.2013

Addressable

for all clients

from the outside!

(5) lcl_bus

Private

Public

​

Protected

Inherited

tank

Geerbt

get_make()

set_make()�get_count()

display_attributes()�estimate_fuel()

​

Addressable

only inside the class

103 of 243

5. Inheritance�Rules for Redefinition of Methods

103

© msg systems ag, 15.01.2013

  • Inherited methods can be redefined in subclasses.
    • Redefined methods must be newly implemented in subclasses
    • The signature of redefined methods cannot be changed
    • Static methods cannot be redefined
  • Static components will be distributed by inheritance: A class can be divided into its non-private static attributes with all its subclasses

The method will be implemented in different ways!

lcl_vehicle

+ estimate_fuel()

lcl_car

+ estimate_fuel()

lcl_truck

+ estimate_fuel()

lcl_bus

+ estimate_fuel()

104 of 243

5. Inheritance�Redefinition for Methods: Example

104

© msg systems ag, 15.01.2013

lcl_truck

- max_cargo

…

+ constructor()

+ estimate_fuel()

lcl_bus

- max_passengers

…

+ constructor()

+ estimate_fuel()

METHOD estimate_fuel.

DATA: weight ...� weight = empty_load + max_cargo.

​

re_fuel = weight * im_distance

* factor.

ENDMETHOD.

METHOD estimate_fuel.

DATA: weight ...� weight = empty_load

+ max_passengers * average_weight.

re_fuel = weight * im_distance

* factor.

ENDMETHOD.

+ max_passengers * average_weight

+ max_cargo

105 of 243

5. Inheritance – Summary

105

© msg systems ag, 15.01.2013

​

You should now be able to

  • define an inheritance relation between classes
  • redefine methods

​

106 of 243

Exercise

106

© msg systems ag, 15.01.2013

Exercise

Inheritance

Class Hierarchies

MIN

HOURS

107 of 243

6. Casting

  • Upcast
  • Downcast
  • Inheritance and Polymorphism

107

© msg systems ag, 15.01.2013

108 of 243

6. Casting�Types of Casts

108

© msg systems ag, 15.01.2013

lcl_vehicle

- make

- model

- ser_no

- color

- n_o_vehicles …

+ constructor()

+ display_attributes()

+ get_count()

lcl_car

- car_type

- max_seats

- acceleration

+ …

+ get_type()

​

lcl_truck

- max_cargo

- n_o_tanks

- n_o_wheels

+ …

+ get_cargo()

lcl_bus

- max_passengers

- lavatory

- television

+ …

+ get_passengers()

Upcast

Downcast

109 of 243

6. Casting�Upcast Principle

109

© msg systems ag, 15.01.2013

DATA: r_vehicle TYPE REF TO lcl_vehicle,� r_truck TYPE REF TO lcl_truck.

CREATE OBJECT r_truck.

* Upcast

r_vehicle = r_truck

r_truck

r_vehicle

r_vehicle

(5) lcl_truck

Public

​

Geerbt

get_make()

get_count()

Redefiniert

display_attributes()

set_attributes()

estimate_fuel()

get_cargo()

…

Inherited

get_make()

get_count()

Redefined

display_attributes()

set_attributes()

estimate_fuel()

r_vehicle = r_truck.

110 of 243

6. Casting�Compatibility und Upcast

110

© msg systems ag, 15.01.2013

DATA: r_vehicle TYPE REF TO lcl_vehicle,

r_truck TYPE REF TO lcl_truck,

level TYPE ty_level.

* Access via the subclass

level = r_truck->estimate_fuel( 1000 ).

​

* Upcast

r_vehicle = r_truck.

​

* Access via the superclass

level = r_vehicle->estimate_fuel( 1000 ).

  • An instance of a subclass can be expected in any context, in which the instance of a superclass can be used
  • Inherited components are addressable from the superclass
  • Generic access of the client!

=

->

r_vehicle

111 of 243

6. Casting�Generic Access?

111

© msg systems ag, 15.01.2013

lcl_rental

lcl_vehicles

lcl_truck

lcl_bus

(1) lcl_car

​

(5) lcl_truck

​

(4) lcl_bus

​

(2) lcl_car

​

1..*

1

Client

(1) lcl_rental

Private

itab

Public

?

112 of 243

6. Casting�Preparation for Generic Access (1)

112

© msg systems ag, 15.01.2013

(1) lcl_rental

Private

vehicle_list

Public

​

​

add_vehicle()

add_vehicle()

...

METHODS: add_vehicle

IMPORTING

im_vehicle TYPE REF TO lcl_vehicle.

...

Client

add_vehicle

(4) lcl_car

(3) lcl_truck

(2) lcl_bus

(5) lcl_car

Up Cast when

handing over!

113 of 243

6. Casting�Preparation for Generic Access(2)

113

© msg systems ag, 15.01.2013

CLASS lcl_rental IMPLEMENTATION.

METHOD add_vehicle.

APPEND im_vehicle TO vehicle_list.� ENDMETHOD.�

METHOD calc_estimated_fuel.� DATA:

r_vehicle TYPE REF TO lcl_vehicle.

re_fuel = 0.

LOOP AT vehicle_list

INTO r_vehicle.

re_fuel = re_fuel

+ r_vehicle->estimate_fuel(

im_distance ).� ENDLOOP.

ENDMETHOD.�ENDCLASS.

(2) lcl_bus

(4) lcl_truck

(3) lcl_bus

lcl_truck

estimate_fuel()

…

lcl_bus

estimate_fuel()

…

(5) lcl_truck

vehicle_list

114 of 243

6. Casting�Polymorphism – Generic Access

114

© msg systems ag, 15.01.2013

METHOD estimate_fuel.

total_weight = max_cargo + weight.

re_fuel = total_weight

* im_distance * factor.

ENDMETHOD.

estimate_fuel

METHOD estimate_fuel.� total_weight = max_passengers

* average_weight + weight.

re_fuel = total_weight � * im_distance * factor.

ENDMETHOD.

estimate_fuel

METHOD calc_estimated_fuel.� DATA: r_vehicle TYPE REF TO lcl_vehicle.� LOOP AT vehicle_list INTO r_vehicle.

ADD r_vehicle->estimate_fuel( im_distance ) TO re_fuel.

ENDLOOP.

ENDMETHOD.

vehicle_list

(5) lcl_truck

Public

Inherited/ redefined

…

estimate_fuel()

(2) lcl_bus

Public

Inherited / redefined

…

estimate_fuel()

r_vehicle->estimate_fuel

115 of 243

6. Casting�Static and dynamic Type of a Reference

115

© msg systems ag, 15.01.2013

  • Static Type of a reference variable
    • is defined using TYPE REF TO
    • remains the same through the program flow
    • defines which attributes and methods can be addressed��
  • Dynamic Type of a reference variable
    • is determined by the assignment
    • can change during the program run
    • defines which implementations are carried out for inherited methods

​

DATA: r_vehicle TYPE

REF TO lcl_vehicle.

r_vehicle

(5) lcl_truck

Private

…

Public

IInherited / redefinied

estimate_fuel()

​

estimate_fuel()

(2) lcl_bus

Private

…

Public

Inherited / redefinied

estimate_fuel()

estimate_fuel()

116 of 243

6. Casting�Comparison to Procedural Programming

116

© msg systems ag, 15.01.2013

DATA: vehicle_list TYPE TABLE OF vehicle_list_type,

vehicle TYPE vehicle_list_type, ...

...

LOOP AT vehicle_list INTO vehicle.

CASE vehicle-category.

WHEN 'TRUCK'.

PERFORM estimate_fuel_truck ...

WHEN 'BUS'.

PERFORM estimate_fuel_bus ...

WHEN 'VAN'.

PERFORM estimate_fuel_van ...

ENDCASE.

ADD fuel TO needed_fuel.

ENDLOOP.

New vehicle category: truck

Procedural

  • Extension e.g. of CASE-Constructions

Object Oriented

  • No change of coding needed.

WHEN 'VAN'.

PERFORM estimate_fuel_van...

ADD r_vehicle->estimate_fuel( )

TO needed_fuel.

name category …

truck1

bus1

bus2

truck2

truck3

van1

vehicle_list

117 of 243

6. Casting

  • Upcast
  • Downcast
  • Inheritance and Polymorphism

117

© msg systems ag, 15.01.2013

118 of 243

6. Casting�Motivation for Downcast

118

© msg systems ag, 15.01.2013

max_cargo

= 50

max_cargo� = 30

METHOD get_max_cargo.

DATA: r_vehicle TYPE REF TO lcl_vehicle.

LOOP AT vehicle_list INTO r_vehicle.

" Problem: is this really a truck?

" Determine the max cargo

ENDLOOP.�ENDMETHOD.

Client

Truck or other vehicle?

(2) lcl_bus

(3) lcl_truck

(4) lcl_car

(5) lcl_truck

(1) lcl_rental

Private

Public

​

​

get_max_cargo()

vehicle_list

119 of 243

6. Casting�Example for Downcast

119

© msg systems ag, 15.01.2013

(2) lcl_bus

(3) lcl_truck

(5) lcl_truck

(1) lcl_rental

Private

Public

​

​

get_max_cargo()

vehicle_list

METHOD get_max_cargo.

DATA: r_vehicle TYPE REF TO lcl_vehicle,� r_truck TYPE REF TO lcl_truck.

LOOP AT vehicle_list INTO r_vehicle.

TRY.

r_truck ?= r_vehicle.

" put max cargo in variable re_cargo... � CATCH cx_sy_move_cast_error.

" react on that cast error

ENDTRY.� ENDLOOP.

ENDMETHOD.

?=

cx_sy_move_cast_error

(4) lcl_car

max_cargo

= 50

max_cargo

= 30

Try and catch

possible errors.

✖

✔

✖

✔

120 of 243

6. Casting

  • Upcast
  • Downcast
  • Inheritance and Polymorphism

120

© msg systems ag, 15.01.2013

121 of 243

6. Casting�Semantic and Use of Inheritance

121

© msg systems ag, 15.01.2013

Rules

  • Redefined methods must have a similar behavior as in the superclass.
  • Any change of the signature (interface) is not possible.
  • Use of inheritance:
    • Generalization/specialization for better structuring of software
    • Polymorphism ⇒ „generic programming“ ⇒�Omission of CASE-structures

122 of 243

6. Casting�Semantic and Use of Inheritance

122

© msg systems ag, 15.01.2013

Rules

  • Inheritance is frequently misused:
    • For pure code reuse
    • Instead of an additional attribute/ aggregation / �role concepts
    • Use of inheritance does not correspond in some cases�to the expectations from the real world�

car

car_red

car_blue

design ?

Superclass�“Rectangular”

Subclass�“square”

design ?

123 of 243

6. Casting – Summary

123

© msg systems ag, 15.01.2013

​

You should now be able to

  • use casts
  • use casts assignments with inheritance to develop generic programs

​

​

124 of 243

Exercise

124

© msg systems ag, 15.01.2013

Exercise

Casting

Polymorphism (Part 1)

​

MIN

HOURS

125 of 243

Exercise

125

© msg systems ag, 15.01.2013

Exercise

Casting

Polymorphism (Part 2)

​

MIN

HOURS

126 of 243

7. Interfaces

  • Interfaces
  • Working with Interfaces
  • Compound Interfaces
  • Polymorphism

126

© msg systems ag, 15.01.2013

127 of 243

7. Interfaces�Motivation for Interfaces

127

© msg systems ag, 15.01.2013

Shared components „Services“

lcl_airplane

lcl_vehicles

lcl_rental

​

​

​

​

Service 1�Service 2

Service 3

...

​

?

...

...

...

...

Interface

lcl_carrier

lcl_hotel

128 of 243

7. Interfaces�Services of the Interfaces

128

© msg systems ag, 15.01.2013

Shared components „Services“

lcl_airplane

lcl_vehicles

lcl_rental

display_partner

check_availability

...

...

...

...

...

lcl_carrier

lcl_hotel

Interface

lcl_travel_agency

describes and uses

129 of 243

7. Interfaces�UML Example

129

© msg systems ag, 15.01.2013

lcl_airplane

lcl_vehicles

lcl_rental

...

...

...

...

lcl_carrier

lcl_hotel

Implementation mehrerer Interfaces möglich!

lcl_travel_agency

«interface»

lif_partners

implements

Client

uses

Implementation of more than one Interface possible!

«interface»

lif_license

130 of 243

7. Interfaces�Definition and Implementation of an Interface

130

© msg systems ag, 15.01.2013

INTERFACE lif_partners.

METHODS: display_partner.

ENDINTERFACE.

CLASS lcl_rental DEFINITION.

PUBLIC SECTION.

INTERFACES lif_partners.

ENDCLASS.

​

  • Definition of the interface��
  • Inclusion of the interface in the “server” classes�

​

  • Implementation is done in classes�
  • No visibility layers in Interfaces; all components are public

CLASS lcl_rental IMPLEMENTATION.

​

METHOD lif_partners~display_partner .

"just call existing method that fits � display_attributes( ).

...

ENDMETHOD.

​

ENDCLASS.

Interface

resolution

operator

lif_partners

lif_partners

lif_partners~display_partner

131 of 243

7. Interfaces�Characteristics of Interfaces

131

© msg systems ag, 15.01.2013

  • Separation of signature (interface) and implementation (class)
    • Client defines protocol, server implements is
    • „Black Box Principle“: Client knows only the interface,�not the implementation
    • loosely coupling between client and server�
  • Polymorphism
    • Generic handling with object from different classes�
  • Abstraction
    • Interfaces as generalizations of the implementing classes�
  • Simulation of multiple inheritance

super1

sub1

sub2

interf

Code 3

Code 2

display_partner

Code 1

Code 4

132 of 243

Exercise

132

© msg systems ag, 15.01.2013

Exercise

Interfaces

Definition of an Interface

MIN

HOURS

133 of 243

7. Interfaces

  • Interfaces
  • Working with Interfaces
  • Compound Interfaces
  • Polymorphism

133

© msg systems ag, 15.01.2013

134 of 243

7. Interfaces�Working with Interface Components

134

© msg systems ag, 15.01.2013

CLASS lcl_rental IMPLEMENTATION.

...� METHOD lif_partners~display_partner.

"special coding to display partners or

"just calling existing method that fits � display_attributes( ).

ENDMETHOD.�

ENDCLASS.

DATA: r_rental TYPE REF TO lcl_rental.

...

�CREATE OBJECT r_rental.

* syntactically possible but not useful:

r_rental->lif_partners~display_partner( ).

implements

Interface resolution operator!

~

«interface»

lif_partners

display_partner()

check_availability()

…

lcl_rental

- name

- vehicle_list

…

+ add_vehicle()

+ display_attributes()

…

​

135 of 243

7. Interfaces�Upcast

135

© msg systems ag, 15.01.2013

DATA: r_rental TYPE REF TO lcl_rental,� r_lif TYPE REF TO lif_partners.

CREATE OBJECT r_rental.

* Up Cast

r_lif = r_rental

r_rental

r_lif

r_lif

(1) lcl_rental

Private

Öffentlich

​

Interface�components

display_partner

check_availability

...

lcl_carrier

lcl_rental

lcl_hotel

«interface»

lif_partners

Upcast

Downcast

136 of 243

7. Interfaces�Use of Interfaces

136

© msg systems ag, 15.01.2013

...

METHODS: add_partner IMPORTING im_partner TYPE REF TO lif_partner.

...

add_partner

(7) lcl_hotel

(1) lcl_rental

(6) lcl_carrier

(9) lcl_travel_agency

Private

​

Public

​

​

add_partner()

add_partner()

partner_list

lif_partner

Up Cast at

handing over!

137 of 243

7. Interfaces�Use of Interfaces

137

© msg systems ag, 15.01.2013

METHOD ...~display_partner.

display_attributes( ). ...

ENDMETHOD.

partner_list

METHOD ...~display_partner . � display_hotel_attributes( ). ... �ENDMETHOD.

METHOD ...~display_partner .

display_rental_data( ). ...

ENDMETHOD.

display_partner

display_partner

display_partner

METHOD display_agency_partners.� DATA: r_partner TYPE REF TO lif_partners. � LOOP AT partner_list INTO r_partner.

r_partner->display_partner( ).

ENDLOOP.

ENDMETHOD.

(6) lcl_carrier

(1) lcl_rental

(7) lcl_hotel

138 of 243

7. Interfaces�Interface References: Down Cast

138

© msg systems ag, 15.01.2013

(7) lcl_hotel

(1) lcl_rental

(6) lcl_carrier

(3) lcl_travel_agency

​

book_flight()

partner_list

METHOD book_flight.

DATA: r_carrier TYPE REF TO lcl_carrier,� r_partner TYPE REF TO lcl_partner.

LOOP AT partner_list INTO r_partner.

TRY.

r_carrier ?= r_partner.

r_carrier->... "Perform necessary operations.

CATCH cx_sy_move_cast_error.� "react on that cast error

ENDTRY.� ENDLOOP.

ENDMETHOD.

r_carrier

✖

✖

✔

?=

cx_sy_move_cast_error

139 of 243

7. Interfaces

  • Interfaces
  • Working with Interfaces
  • Compound Interfaces
  • Polymorphism

139

© msg systems ag, 15.01.2013

140 of 243

7. Interfaces –�Compound Interfaces

140

© msg systems ag, 15.01.2013

Problem:�Extension of the Interface?

lcl_rental

lcl_hotel

lcl_carrier

«interface»

lif_partners

implements

book_room()

?

141 of 243

7. Interfaces –�Compound Interfaces

141

© msg systems ag, 15.01.2013

«interface»

lif_room_booking

lcl_rental

lcl_hotel

lcl_carrier

«interface»

lif_partners

implements

Solution:�Compound Interfaces

implements

interfaces:

142 of 243

7. Interfaces – �Compound Interfaces: Example

142

© msg systems ag, 15.01.2013

INTERFACE lif_partners.

METHODS display_partner.

ENDINTERFACE.

INTERFACE lif_room_booking.

INTERFACES lif_partners.

METHODS book_room.

ENDINTERFACE.

CLASS lcl_hotel DEFINITION.

PUBLIC SECTION.

INTERFACES lif_room_booking.

ENDCLASS.

CLASS lcl_hotel IMPLEMENTATION.

METHOD lif_partner~display_partner.

ENDMETHOD.

METHOD lif_room_booking~book_room.

ENDMETHOD.

ENDCLASS.

DATA: i_partner TYPE REF TO lif_partners,

i_room_book TYPE REF TO lif_room_booking,

...

i_partner = i_room_book. "Narrowing Cast

​

i_room_book->lif_partner~display_partner( ).

* i_partner->display_partner( ) also possible

​

i_room_book ?= i_partner. "Widening Cast

INTERFACES

143 of 243

7. Interfaces – Summary

143

© msg systems ag, 15.01.2013

​

You should now be able to

  • define and implement
  • develop generic programs using polymorphism and interfaces

​

144 of 243

Exercise

144

© msg systems ag, 15.01.2013

Exercise

Interfaces

Use of Interfaces

MIN

HOURS

145 of 243

8. Events

  • Define and trigger events
  • Register and handle events

145

© msg systems ag, 15.01.2013

146 of 243

8. Events – Overview

146

© msg systems ag, 15.01.2013

Recipient / Handler

* main program

CREATE OBJECT r_car EXPORTING …

Car rental company

Auto

Registration office

...

Sender

Event: vehicle_created

147 of 243

8. Events –�Properties

147

© msg systems ag, 15.01.2013

  • Looser coupling than using method invocation
    • Trigger object announces a change of state
    • Handler objects can register to event
  • Another communication model

Sender is not aware of the receiver;�the reaction of the receiver is of no interest for the sender.

  • Application
    • GUI implementation
    • Conformity to other object models:� COM, ActiveX Controls, OpenDoc ...

​

148 of 243

8. Events –�Triggering and Handling Events: Overview

148

© msg systems ag, 15.01.2013

  • Trigger events

Class defines an event� (EVENTS, CLASS-EVENTS)

Object or class triggers the event� (RAISE EVENT)�

  • Handle events

Handler class defines and implements the handler method� ([CLASS-]METHODS... FOR EVENT ... OF ...)

„Handler object” or handler class is registered to events of specific objects/ classes at runtime� (SET HANDLER)

Rules

1

2

3

4

149 of 243

8. Events – �Defining and Triggering Events: Syntax

149

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.

METHODS constructor IMPORTING ... .

EVENTS vehicle_created.

...

ENDCLASS.

​

CLASS lcl_vehicle IMPLEMENTATION.

METHOD constructor.

...

RAISE EVENT vehicle_created

ENDMETHOD.

ENDCLASS.

CLASS <classname> IMPLEMENTATION.

METHOD <methodname>.

RAISE EVENT <event> EXPORTING <ex_par> = <act_par>.

​

car

RAISE EVENT

EVENTS

1.

RAISE EVENT

2.

vehicle_created

CLASS <classname> DEFINITION.

EVENTS: <event> EXPORTING VALUE(<ex_par>) TYPE <type>.

EVENTS

VALUE(

)

Typing of all parameters

150 of 243

8. Events – �Event handling and registering

150

© msg systems ag, 15.01.2013

Interested in this event?

carrier

registration

office

rental

car1

car2

truck

Sender

Handler

vehicle_created

vehicle_created

vehicle_created

151 of 243

8. Events –�Handling method

151

© msg systems ag, 15.01.2013

rental

add_vehicle

CLASS <class_handle> DEFINITION.

METHODS: <on_event> FOR EVENT <event>

OF <class/interfacename>

IMPORTING <ex_par1> ... <ex_parN> SENDER.

CLASS lcl_rental DEFINITION.

...

PRIVATE SECTION.

METHODS: add_vehicle FOR EVENT vehicle_created OF lcl_vehicle

IMPORTING SENDER.

ENDCLASS.

car1

3.

METHODS

FOR EVENT

OF

IMPORTING

SENDER

add_vehicle

OF

IMPORTING SENDER

vehicle_created

No Typing, only enumeration

152 of 243

8. Events –�Registering Event Handling: Syntax

152

© msg systems ag, 15.01.2013

CLASS lcl_rental IMPLEMENTATION.

METHOD constructor.

SET HANDLER add_vehicle FOR ALL INSTANCES. � ENDMETHOD.

METHOD ...

ENDCLASS.

SET HANDLER <ref_handle>-><on_event>

FOR <ref_sender> | FOR ALL INSTANCES

[ACTIVATION <var>].

CLASS lcl_rental DEFINITION.

...

PRIVATE SECTION.

METHODS: add_vehicle FOR EVENT vehicle_created OF ...

ENDCLASS.

rental

add_vehicle

car1

add_vehicle

SET HANDLER add_vehicle FOR ALL INSTANCES

4.

vehicle_created

153 of 243

8. Events –�Registration/Deregistration: Handler Tables

153

© msg systems ag, 15.01.2013

registration

office

Handler table of car2

car2

r_car

registration

office

Handler table of car1

car1

r_car

rental

vehicle_created (Event)

handling registered

method object

add_vehicle

reg_vehicle

vehicle_created (Event)

handling registered

method object

add_vehicle

reg_vehicle

154 of 243

8. Events –�Event Handling: Properties

154

© msg systems ag, 15.01.2013

  • Event handling is performed sequentially.
  • The order od invocation of handler methods is not defined.
  • Registered objects won’t be erased by the Garbage Collector.
  • The visibility of an event sets who can handle an Event.
  • The visibility of a handler method sets who can use a SET-HANDLER-instruction.

A handler method can have even though only the same or a more restrictive visibility than the event related to it.

​

​

​

Event Handler

Public Private ✖

Private Public ✔

​

155 of 243

8. Events –�Summary

155

© msg systems ag, 15.01.2013

​

You should now be able to

  • define and trigger events
  • handle events
  • register and deregister event handling
  • explain the key differences between explicit method calls and event-controlled method calls

156 of 243

Exercise

156

© msg systems ag, 15.01.2013

Exercise

Event Triggering

and Handling

MIN

HOURS

157 of 243

9. Global Classes/Interfaces

  • The Class Builder
  • Working with Global Classes/Interfaces
  • Application Example: ALV Grid Control

157

© msg systems ag, 15.01.2013

158 of 243

9. Global Classes/Interfaces�Rewind: Local Classes/Interfaces

158

© msg systems ag, 15.01.2013

REPORT prog1.

​

CLASS lcl_airplane DEFINITION.

...

ENDCLASS.

...

REPORT prog2.

​

DATA: r_airplane

TYPE REF TO lcl_airplane.

...

Local Program Classes

    • Local classes are visible only in the program, in which they are defined.
    • No global access possible
    • Not created in Repository, no Where-Used List etc.

Program-1

Program-2

lcl_airplane

lcl_airplane

159 of 243

9. Global Classes/Interfaces

159

© msg systems ag, 15.01.2013

  • Classes/Interfaces in ABAP-Repository (= Global classes)�
  • Access from any program possible via TYPE REF TO�
  • Client namespace for global classes and Interfaces:�Y*, Z* or a special customer namespace�
  • Where-Used List is possible�
  • Development tool in the ABAP-Workbench: Class Builder�Tool for creation, testing and maintenance of �global classes and interfaces
    • Takes on the creation of the whole framework coding�e.g. CLASS <name> DEFINITION
    • Manages the Include-Data, in which the code is stored
    • Graphical Editor

160 of 243

9. Global Classes/Interfaces�Global Classes in SE80 – Created in the Object Navigator

160

© msg systems ag, 15.01.2013

Creation of a Class using the

Object Navigator:

161 of 243

9. Global Classes/Interfaces�Class Builder: Attributes

161

© msg systems ag, 15.01.2013

Defining the attributes of a class

162 of 243

9. Global Classes/Interfaces�Class Builder: Methods

162

© msg systems ag, 15.01.2013

Defining methods of a class

Set the

signature parameter of the

selected method,

Here: CONSTRUCTOR

Redefinition�Undo Redefinition

163 of 243

9. Global Classes/Interfaces�Class Builder: Definition of Method Signatures

163

© msg systems ag, 15.01.2013

Set the

signature parameter

Back to method list

164 of 243

9. Global Classes/Interfaces�Class Builder: Exception Interface

164

© msg systems ag, 15.01.2013

Set the

possible exceptions

Back to method list

165 of 243

9. Global Classes/Interfaces�Class Builder: Defining Interfaces

165

© msg systems ag, 15.01.2013

1) Declaring the global interfaces in a global class

2) Implementation of methods from a global class

166 of 243

9. Global Classes/Interfaces�Class Builder: Implementation of Methods

166

© msg systems ag, 15.01.2013

Signature displayed to help with the implementation of the method

167 of 243

9. Global Classes/Interfaces�Class Builder: Inheritance

167

© msg systems ag, 15.01.2013

Make superclass known

168 of 243

9. Global Classes/Interfaces�Class Builder: Testing Environment

168

© msg systems ag, 15.01.2013

Test class

Create instance

Call methods

169 of 243

9. Global Classes/Interfaces

  • The Class Builder
  • Working with Global Classes/Interfaces
  • Application Example: ALV Grid Control

169

© msg systems ag, 15.01.2013

170 of 243

9. Global Classes/Interfaces�Global Classes in the Object Navigator

170

© msg systems ag, 15.01.2013

Left: Navigation Tree

Right: Editing an ABAP Program in the Editor

171 of 243

9. Global Classes/Interfaces�Class Builder: CREATE OBJECT

171

© msg systems ag, 15.01.2013

Representation of a class in the Navigation Tree enables the access to the class components

Drag&Drop of the constructor or the class name, generates CREATE OBJECT.

172 of 243

9. Global Classes/Interfaces�Class Builder: CALL METHOD

172

© msg systems ag, 15.01.2013

Drag&Drop of a method generates a method call.

173 of 243

9. Global Classes/Interfaces

  • The Class Builder
  • Working with Global Classes/Interfaces
  • Application Example: ALV Grid Control

173

© msg systems ag, 15.01.2013

174 of 243

9. Global Classes/Interfaces�The ALV Grid Control

174

© msg systems ag, 15.01.2013

Details

Sort

Search

Filter

Sum

Print

CL_GUI_ALV_GRID

Views�(Table, Grid, Excel)

Export

Chart

175 of 243

9. Global Classes/Interfaces�Integrating a Grid-Control instance in a dialog program

175

© msg systems ag, 15.01.2013

Dynpro

Area

Custom

Container

Control

ALV

Grid

Control

For using the ALV Grid Control, two classes are needed.

(1) cl_gui_custom_container

​

Private

Public

(3) cl_gui_alv_grid

Private

Public

176 of 243

9. Global Classes/Interfaces�Displaying data in an ALV-Grid

176

© msg systems ag, 15.01.2013

...

DATA: go_container TYPE REF TO cl_gui_custom_container,

go_grid TYPE REF TO cl_gui_alv_grid .

...

CREATE OBJECT go_container

EXPORTING container_name = 'CONTAINER_1'

...

​

CREATE OBJECT go_grid

EXPORTING i_parent = go_container

...

​

go_grid->set_table_for_first_display(

i_structure_name = 'SPFLI'

it_outtab = gt_flights).

...

​

(1) cl_gui_alv_grid

​

Private

Public

(1) cl_gui_custom...

Private

​

Public

cl_gui_custom_container

cl_gui_alv_grid

set_table_for_first_display

177 of 243

9. Global Classes/Interfaces�Summary

177

© msg systems ag, 15.01.2013

​

You should now be able to:

  • describe the difference between local and global classes/interfaces
  • create global classes/interfaces using the Class Builder

178 of 243

Exercise

178

© msg systems ag, 15.01.2013

Exercise

Global Classes

Creating a Class

MIN

HOURS

179 of 243

10. Programming Techniques

  • Abstract and Final Classes
  • Visibility of Constructors
  • Strings
  • Friendship
  • Persistent Objects

179

© msg systems ag, 15.01.2013

180 of 243

10. Programming Techniques�Abstract Classes

180

© msg systems ag, 15.01.2013

CLASS lcl_vehicle DEFINITION ABSTRACT.

PUBLIC SECTION.

METHODS:

estimate_fuel_consumption ABSTRACT� IMPORTING ...

ENDCLASS.

  • Abstract Classes cannot be instantiated themselves (but their subclasses are)

References to such abstract classes can therefore be used for polymorphic

access to subclass instances.

  • Abstract (instance) methods are defined in a class, but not implemented

They have to be redefined in the subclasses

Class cannot be instantiated

Method is not implemented in this class

ABSTRACT

ABSTRACT

181 of 243

10. Programming Techniques�Final Classes – Final Methods

181

© msg systems ag, 15.01.2013

CLASS lcl_truck DEFINITION FINAL

INHERITING FROM lcl_vehicle.

...

ENDCLASS.

CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle.

PUBLIC SECTION.

METHODS:

estimate_number_of_free_seats FINAL.

ENDCLASS.

  • Final methods cannot be redefined in subclasses.
  • Final classes cannot have subclasses.

FINAL

FINAL

lcl_bus

lcl_vehicle

lcl_truck

...

...

...

182 of 243

10. Programming Techniques

  • Abstract and Final Classes
  • Visibility of Constructors
  • Strings
  • Friendship
  • Persistent Objects

182

© msg systems ag, 15.01.2013

183 of 243

10. Programming Techniques�Issue with multiple instantiation

183

© msg systems ag, 15.01.2013

(1) lcl_daten

​

Private

Public

Function 1

Function 2

Function 3

Function 4

Change

(2) lcl_daten

​

Private

Public

Change

STOP

184 of 243

10. Programming Techniques�Who can instantiate classes?

184

© msg systems ag, 15.01.2013

  • The instantiation of classes can be restricted:�CLASS cl_class DEFINITION ...
    • CREATE PUBLIC�Each user (Client) can create class instances.�(Default)
    • CREATE PROTECTED�Only the class itself and all its subclasses can create instances of this class.
    • CREATE PRIVATE�Only the class itself can create instances of itself..
  • Thus, the visibility of the constructor is�implicitly controlled.
  • Possible use: �„Singleton“ design pattern

Client

(1) lcl_singleton

​

Private

Public

​

​

get_instance

mo_singl

185 of 243

10. Programming Techniques�Singleton

185

© msg systems ag, 15.01.2013

Two possibilities to develop a Singleton:�

  • lazy creation�Insantiating on first access���
  • eager creation�Generation in the class constructor

�

METHOD get_instance.

IF mo_single IS INITIAL.

CREATE OBJECT mo_single.

ENDIF.

​

ro_single = mo_single.

ENDMETHOD.

lcl_singleton

- mo_single:lcl_singleton

+ get_instance():lcl_singleton

METHOD class_constructor.

CREATE OBJECT mo_single.

ENDMETHOD.

​

METHOD get_instance.

ro_single = mo_single.

ENDMETHOD.

lcl_singleton

- mo_single:lcl_singleton

+ get_instance():lcl_singleton

+ class_constructor()

186 of 243

Exercise

186

© msg systems ag, 15.01.2013

Exercise

Programming Techniques

Singleton

MIN

HOURS

187 of 243

10. Programming Techniques

  • Abstract and Final Classes
  • Visibility of Constructors
  • Strings
  • Friendship
  • Persistent Objects

187

© msg systems ag, 15.01.2013

188 of 243

10. Programming Techniques�ABAP-Strings

188

© msg systems ag, 15.01.2013

DATA: lv_str TYPE c LENGTH 20.

​

lv_str = 'Hello World!'.

​

" Truncated (not wide enough!)

CONCATENATE lv_str lv_str

INTO lv_str.

​

" Syntax error (not wide enough!)

lv_str = lv_str+10(15).

​

" Ugly: * no localization,

" * space before '.',

" * lengthy, error-prone.

lv_str = sy-datum.

CONCATENATE

'Today is ' lv_str '.'

INTO lv_str

SEPARATED BY space.

CALL METHOD lo->meth( lv_str ).

DATA: lv_str TYPE string.

​

lv_str = `Hello World!`.

​

" No truncation

lv_str = lv_str && lv_str.

​

​

" No syntax- but runtime error

lv_str = lv_str+10(15).

​

" Pretty: * localization,

" * space before '.',

" * short,

" * directly usable

" in method call

CALL METHOD lo_meth(

|Today is { sy-datum

DATE = USER }.| ).

​

!'.

!`.

189 of 243

10. Programming Techniques

  • Abstract and Final Classes
  • Visibility of Constructors
  • Strings
  • Friendship
  • Persistent Objects

189

© msg systems ag, 15.01.2013

190 of 243

10. Programming Techniques�Friendship

190

© msg systems ag, 15.01.2013

  • In some cases, classes have to work together so closely that one or both classes need access to the others protected and private components.
    • High-performance direct access to the data in a friendship-grating class
    • Distribution of various services to common data over different classes
    • Formation of packages

​

Package

Friend

Grants friendship

(4) lcl_flight_planer

Public

​

plan_flight()

schedule()

(3) lcl_flight_factory

​

Public

​

create_flight()�get_flight()

delete_flight()

Friend

(5) lcl_flight_data

​

Private

flight_list

191 of 243

10. Programming Techniques

  • Abstract and Final Classes
  • Visibility of Constructors
  • Strings
  • Friendship
  • Persistent Objects

191

© msg systems ag, 15.01.2013

192 of 243

10. Programming Techniques�Persistence Services

192

© msg systems ag, 15.01.2013

Database

​

ABAP Program

Persistence Service

Transient Objects

Persistent data in transparent tables

Read / write objects

193 of 243

10. Programming Techniques�Characteristics of Persistence Services

193

© msg systems ag, 15.01.2013

  • The Objects of a running ABAP program are transient.
  • The Persistence Services allows working with persistent objects.
  • Persistent classes are created�in the class builder������
  • Tasks of Persistence Services:
    • Loading objects from the database
    • Managing object changes
    • Saving objects in the database

194 of 243

10. Programming Techniques�The Class Agent

194

© msg systems ag, 15.01.2013

...

DATA: r_carrier TYPE REF TO cl_carrier,

r_agent TYPE REF TO ca_carrier,

carrname TYPE s_carrname.

​

TRY.

r_agent = ca_carrier=>agent.

​

r_carrier = r_agent->get_persistent( i_carrid = 'LH' ).

carrname = r_carrier->get_carrname( ).

WRITE: 'LH: ', carrname.

CATCH cx_os_object_not_found.

ENDTRY.

  • Within the Persistence Services, the Class Agent takes over the management of the persistent objects.
    • The actor provides several services (method calls), for managing the objects and the encapsulated object data
    • The class actor is a singleton instance, addressed with the public static attribute agent.

The agent (actor), a singleton of the class CA_CARRIER and friend of the persistent classCL_CARRIER

agent

195 of 243

10. Programming Techniques�Summary

195

© msg systems ag, 15.01.2013

​

You should now be able to

  • Create and describe abstract and final classes
  • Describe the visibility of the constructors
  • Define friend relationships between classes
  • Describe the Persistence Services

196 of 243

Exercise

196

© msg systems ag, 15.01.2013

Exercise

Programming Techniques

Friendship

MIN

HOURS

197 of 243

11. Exception Handling

  • Predefined and Selfdefined Class-based Exceptions
  • Exception raising, handling and propagating

197

© msg systems ag, 15.01.2013

198 of 243

11. Exception Handling�Class-Based Exceptions – Sequence Diagram

198

© msg systems ag, 15.01.2013

get_fuel_level( )

get_fuel_level( )

re_level

re_level

:lcl_car

:lcl_tank

«exception»

sensor_failed

alert( )

break

[Fill level sensor failed ]

:lcl_driver

199 of 243

11. Exception Handling�Class-Based Exceptions – Sequence Diagram (Propagation)

199

© msg systems ag, 15.01.2013

get_fuel_level( )

get_fuel_level( )

re_level

re_level

:lcl_car

:lcl_tank

«exception»

sensor_failed

pit_stop( )

break

[Fill level sensor failed ]

:lcl_driver

200 of 243

11. Exception Handling�Class-Based Exceptions – Overview

200

© msg systems ag, 15.01.2013

Exception class (predefined or your own)

...

​

RAISE EXCEPTION TYPE cx_exception

[EXPORTING attr1 = ...

attr2 = ...].

...

* Exception handling

...

ABAP Runtime System

Exception raised using the ABAP statement or by the runtime environment

zcx_exception

​

…

​

​

…

ABAP Program

201 of 243

11. Exception Handling�Handling Exceptions

201

© msg systems ag, 15.01.2013

TRY.

   " Perform normal operation

...

​

CATCH cx_... cx_... ... [INTO lx_exc1].

​

    ...   

                 

CATCH cx_... ... [INTO lx_exc2].

​

    ...   

                 

CATCH cx_root [INTO lx_root].

​

    ...   

                 

CLEANUP.

​

    ...

​

ENDTRY.

​

Statements for which exceptions are to be handled

Behandler für die angegebenen Ausnahmeklassen und deren Unterklassen

Clean up, if there is no exception handler available

Handlers for the specified exception classes and their subclasses

Handlers for all exception objects of other classes

202 of 243

11. Exception Handling�Exception Classes: The Inheritance Hierarchy

202

© msg systems ag, 15.01.2013

cx_static_check

cx_dynamic_check

cx_no_check

cx_sy_move_cast_error

cx_sy_arithmetic_error

cx_sy_arithmetic_overflow

cx_root

​

- textid

- kernel_errid

...

+ get_text()

+ get_source_position()

203 of 243

11. Exception Handling�Example: Handling a Predefined Exception

203

© msg systems ag, 15.01.2013

PARAMETERS: int1 TYPE i,

int2 TYPE i.

​

DATA: result TYPE i,

lx_exc TYPE REF TO cx_root.

​

...

​

TRY.

result = int1 * int2.

WRITE result.

CATCH cx_sy_arithmetic_overflow INTO lx_exc.

MESSAGE lx_exc TYPE 'I' DISPLAY LIKE 'E'.

ENDTRY.

​

...

​

If an overflow error occurs, the runtime system raises the cx_sy_arithmetic_overflow exception

204 of 243

11. Exception Handling�Example: Using your own exceptions

204

© msg systems ag, 15.01.2013

CLASS lcl_airplane IMPLEMENTATION.

...

METHOD get_technical_attributes.

​

SELECT SINGLE weight tankcap FROM saplane

INTO (ex_weight, ex_tankcap)

WHERE planetype = im_type.

IF sy-subrc <> 0.

ex_weight = 100000.

ex_tankcap = 10000.

ENDIF.

​

ENDMETHOD.

...

ENDCLASS.

CLASS lcl_airplane DEFINITION.

...

METHODS get_technical_attributes

IMPORTING im_type TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity.

...

ENDCLASS.

Program adaptation: If there are no table entries ⇒ raise and handle own exception

205 of 243

11. Exception Handling�Creating Exception Classes

205

© msg systems ag, 15.01.2013

206 of 243

11. Exception Handling�Define your own Attributes and Exception Texts

206

© msg systems ag, 15.01.2013

Exception texts describe exception in more detail

Your own attributes provide additional information

207 of 243

11. Exception Handling�Raising and Handling selfdefined exceptions

207

© msg systems ag, 15.01.2013

METHOD get_technical_attributes.

​

DATA: lx_exc TYPE REF TO cx_root,

text TYPE string.

​

TRY.

SELECT SINGLE weight tankcap FROM saplane

INTO (ex_weight, ex_tankcap)

WHERE planetype = im_type.

​

IF sy-subrc <> 0.

RAISE EXCEPTION TYPE zcx_wrong_planetype

EXPORTING planetype = im_type.

ENDIF.

" Operate on valid values

" in ex_weight and ex_tankcap

​

CATCH zcx_wrong_planetype INTO lx_exc.

text = lx_exc->get_text( ).

MESSAGE text TYPE 'I'.

ENDTRY.

ENDMETHOD.

Example:

im_type = 727-301

208 of 243

11. Exception Handling�Propagating Exceptions

208

© msg systems ag, 15.01.2013

CLASS class IMPLEMENTATION.

...

METHOD meth.� ...� RAISE EXCEPTION TYPE cx_exception.� ENDMETHOD.

ENDCLASS.

CLASS class DEFINITION.

...

METHODS meth IMPORTING <im_parameter>

EXPORTING <ex_parameter>

RAISING cx_exception.

...

ENDCLASS.

REPORT propagate_exceptions.

...

DATA r_obj TYPE REF TO class.

...

​

TRY.

r_obj->meth( EXPORTING ...

IMPORTING ... ).

​

CATCH cx_exception .

...

​

ENDTRY.

  • Exceptions that occur in procedures do not necessarily need to be handled there; they can be passed along to the calling program.

②

①

RAISING cx_exception

RAISE EXCEPTION TYPE cx_exception

CATCH cx_exception

209 of 243

11. Exception Handling�Taking up exceptions in the method signature

209

© msg systems ag, 15.01.2013

210 of 243

11. Exception Handling�Resumable Exceptions – Sequence Diagram

210

© msg systems ag, 15.01.2013

get_fuel_level( )

get_fuel_level( )

re_level

:lcl_car

:lcl_driver

:lcl_tank

«resumable_exception»

sensor_failed

RESUME ...

re_level

break

[ Fill level sensor failed ]

211 of 243

11. Exception Handling�Example: Propagating Exceptions

211

© msg systems ag, 15.01.2013

METHOD get_technical_attributes.

​

SELECT SINGLE weight tankcap

FROM saplane

INTO (ex_weight, ex_tankcap)

WHERE planetype = im_type.

​

IF sy-subrc <> 0.

​

RAISE EXCEPTION

TYPE zcx_wrong_planetype

EXPORTING pl_type = im_type.

​

ENDIF.

ENDMETHOD.

CLASS lcl_airplane DEFINITION.

METHODS display_attributes.

METHODS get_technical_attributes

IMPORTING im_type TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity

RAISING zcx_wrong_planetype .

ENDCLASS.

METHOD display_attributes.

DATA: lx_exc TYPE REF TO cx_root,

text TYPE string.

...

TRY.

get_technical_attributes(

EXPORTING im_type = planetype

IMPORTING ex_weight = weight

ex_tankcap = cap ).

WRITE: /'Gewicht:'(003), weight,

'Tankkapazität:'(004), cap.

CATCH zcx_wrong_planetype INTO lx_exc.

MESSAGE lx_exc TYPE 'I'.

ENDTRY.

ENDMETHOD.

RAISING zcx_wrong_planetype

CATCH zcx_wrong_planetype INTO lx_exc

RAISE EXCEPTION

TYPE zcx_wrong_planetype

EXPORTING pl_type = im_type

①

②

212 of 243

11. Exception Handling�Declarable Exceptions

212

© msg systems ag, 15.01.2013

  • These exceptions can be handled, otherwise they are forwarded automatically; no explicit forwarding using RAISING addition possible;
  • No review by the syntax check

​

  • These exceptions need to be handled or explicitly forwarded using the RAISING addition;
  • No review by the syntax check
  • These exceptions need to be handled or explicitly forwarded using the RAISING addition;
  • Review by the syntax check

cx_static_check

cx_dynamic_check

cx_no_check

cx_root

213 of 243

11. Exception Handling�Summary

213

© msg systems ag, 15.01.2013

​

You should now be able to

  • Create exception classes
  • Trigger exceptions in programs
  • Handle exceptions
  • Propagate exceptions

214 of 243

Exercise

214

© msg systems ag, 15.01.2013

Exercise

Exception Handling

Class-based Exceptions

MIN

HOURS

215 of 243

12. Dynamic Programming

  • Field Symbols
  • Dynamic Access
  • Data References
  • Dynamic Determination of Object Properties
  • Code Construct with Dynamic Programming

215

© msg systems ag, 15.01.2013

216 of 243

12. Dynamic Programming�Field Symbols

216

© msg systems ag, 15.01.2013

Field symbols

  • … point to data, table entries, structure components (fields)
  • … are "assigned".
  • … can be of data type ANY.
  • … can be identified by the notation with angle brackets <fs>.
  • INTO vs. ASSIGNING resp. IS INITIAL vs. IS ASSIGNED

FIELD-SYMBOLS: <fs> TYPE <Structure>,

<fs> TYPE TABLE OF <Structure>,

<fs> TYPE ANY,

<fs> TYPE ANY TABLE.

<fsob>

<fs1>

<fs2>

<fs3>

Index Name Fname Age Wage

1 Huber Lotte 18 1.200

2 Maier Klaus 24 1.800

3 Berg Lisa 35 2.400

4 Reiß Tim 24 1.800

217 of 243

12. Dynamic Programming�Field Symbols – ASSIGNING vs. INTO

217

© msg systems ag, 15.01.2013

DATA: tab1 TYPE TABLE OF struct,

tab2 TYPE TABLE OF struct,

tab3 TYPE TABLE OF struct.

​

FIELD-SYMBOLS: <fs> TYPE struct.

​

* make <fs> point onto

* first record in a table

READ TABLE tab1 INDEX 1

ASSIGNING <fs>.

​

* make <fs> point onto

* first record in a another table

READ TABLE tab2 INDEX 2

ASSIGNING <fs>.

​

* copy record from a third table into

* the table row pointed at by <fs>

READ TABLE tab3 INDEX 1

INTO <fs>.

<fs>

1

2

3

1

2

3

Index Name Fname

1 Huber Lotte

2 Maier Klaus

Index Name Fname

1 Berg Lisa

2 Reiß Tim

Index Name Fname

1 Kraus Karl

2 Moser Hans

Kraus Karl

ASSIGNING <fs>

ASSIGNING <fs>

INTO <fs>

218 of 243

12. Dynamic Programming�Field Symbols – Casting on ASSIGN

218

© msg systems ag, 15.01.2013

TYPES: BEGIN OF st_date,

year(4) TYPE n,

month(2) TYPE n,

day(2) TYPE n,

END OF st_date.

�* Option 1: Implicitly

FIELD-SYMBOLS <fs> TYPE st_date.

ASSIGN sy-datum TO <fs> CASTING.

​

* Option 2: Explicit

FIELD-SYMBOLS <fs> TYPE ANY.

ASSIGN sy-datum TO <fs>

CASTING TYPE st_date.

​

* Access after cast:

WRITE: / <fs>-year, <fs>-month, <fs>-day.

  • The access is interpreted as though the data object had the data type of the field symbol.
  • In addition, he casting type can be explicitly specified.

20120221

<fs>

CASTING

CASTING TYPE

TYPE ANY

219 of 243

12. Dynamic Programming

  • Field Symbols
  • Dynamic Access
  • Data References
  • Dynamic Determination of Object Properties
  • Code Construct with Dynamic Programming

219

© msg systems ag, 15.01.2013

220 of 243

12. Dynamic Programming�Statements with Dynamic Attributes

220

© msg systems ag, 15.01.2013

Replacing a literal with a variable:

CALL TRANSACTION 'T_CODE'.

SUBMIT report.

SET PF-STATUS 'STATUS_NAME'

EXCLUDING 'FC1' 'FC2' ... .

Replacing an identifier with a variable in brackets (without blanks):

Replacing an enumeration with an internal table:

Replacing conditions with an internal table :

LOOP AT table ASSIGNING <fs>

WHERE age = 16 OR age = 17

AND salary <= 1000 ... .

lv_tcode = 'T_CODE'. �CALL TRANSACTION lv_tcode.

lv_report_name = 'REPORT'. �SUBMIT (lv_report_name).

* fill internal table lt_exclude

* with function codes�SET PF-STATUS 'STATUS_NAME'

EXCLUDING lt_exclude.

* ... fill internal table

* lt_cond with conditions.�LOOP AT table INTO wa

WHERE lt_cond.

lv_tcode

(lv_report_name)

lt_exclude

lt_cond

221 of 243

12. Dynamic Programming�Calling methods dynamically

221

© msg systems ag, 15.01.2013

​

ptab

​

​

​

​

etab

NAME KIND VALUE

TYPE-POOLS: abap.

​

DATA: meth TYPE abap_methname,

ptab TYPE abap_parmbind_tab,

etab TYPE abap_excpbind_tab.

...

meth = 'METHOD_NAME'.

​

* Fill ptab and etab

...

CALL METHOD ref->(meth)

PARAMETER-TABLE ptab

EXCEPTION-TABLE etab.

Reference to the actual parameter

TYPE REF TO

Transfer type

Formal parameter name

Exception name

sy-subrc value

NAME VALUE

PARAMETER-TABLE ptab

EXCEPTION-TABLE etab

abap_parmbind_tab

abap_excpbind_tab

abap_methname

222 of 243

12. Dynamic Programming

  • Field Symbols
  • Dynamic Access
  • Data References
  • Dynamic Determination of Object Properties
  • Code Construct with Dynamic Programming

222

© msg systems ag, 15.01.2013

223 of 243

12. Dynamic Programming�Data References

223

© msg systems ag, 15.01.2013

lr_ref

lv_num

​

TYPES reftype { TYPE REF TO type_name |

LIKE REF TO do_name |

TYPE REF TO data }.

​

DATA ref { TYPE REF TO type_name |

LIKE REF TO do_name |

TYPE REF TO data }.

​

GET REFERENCE OF dataobject INTO ref.

​

DATA: lr_ref TYPE REF TO i,

lv_num TYPE i VALUE 15.

​

​

GET REFERENCE OF lv_num INTO lr_ref.���

lr_ref

lv_num

15

15

Get reference to a data object

Generic type

Any completely specified type

GET REFERENCE OF lv_num INTO lr_ref.

224 of 243

12. Dynamic Programming�Example: Dynamic Method Calls

224

© msg systems ag, 15.01.2013

TYPE-POOLS abap.

DATA: ptab TYPE abap_parmbind_tab,

wa_ptab LIKE LINE OF ptab,

meth TYPE abap_methname,

gd_make TYPE string VALUE `VOLVO`.

​

wa_ptab-name = 'EX_MAKE'.

GET REFERENCE OF gd_make

INTO wa_ptab-value = ref.

INSERT wa_ptab INTO TABLE ptab.

​

meth = 'GET_MAKE'.

CALL METHOD r_truck->(meth)

PARAMETER-TABLE ptab.

​

WRITE gd_make.

CLASS lcl_vehicle DEFINITION.

...

METHODS get_make

EXPORTING ex_make TYPE string.

...

​

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.

...

METHOD get_make.

ex_make = make.

ENDMETHOD.

...

ENDCLASS.

ptab

​

​

gd_make

`VOLVO`

Situation after the dynamic method call:

NAME KIND VALUE

EX_MAKE

225 of 243

12. Dynamic Programming�Creating Data Objects at Runtime

225

© msg systems ag, 15.01.2013

DATA ref { TYPE REF TO type_name | LIKE REF TO var }.

CREATE DATA ref.

DATA ref TYPE REF TO data.

CREATE DATA ref TYPE { type_name | itab_type_def }.

PARAMETERS pa_tab TYPE dd021-tabname.

DATA ref_itab TYPE REF TO data.

​

​

CREATE DATA ref_itab TYPE STANDARD TABLE

OF (pa_tab)

WITH DEFAULT KEY.

ref_itab

Standard table with default key and row type corresponding to the content of the data object pa_tab

①

②

Typing can also take place dynamically

CREATE DATA

(pa_tab)

226 of 243

12. Dynamic Programming�Dereferencing data references

226

© msg systems ag, 15.01.2013

ASSIGN ref->* TO <fs> [CASTING ... ].

​

PARAMETERS pa_tab TYPE dd021-tabname.

DATA ref_itab TYPE REF TO data.

​

FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.

​

​

CREATE DATA ref_itab TYPE STANDARD TABLE

OF (pa_tab)

WITH DEFAULT KEY.

​

ASSIGN ref_itab->* TO <fs_itab>.

​

SELECT * FROM (pa_tab) INTO TABLE <fs_itab>.

​

ref_itab fs_itab

​

->*

You can address the contents of the internal table using the field symbol.

227 of 243

12. Dynamic Programming�Example: Output the contents of an arbitrary database table

227

© msg systems ag, 15.01.2013

PARAMETERS pa_dbtab TYPE dd02l-tabname

DEFAULT 'SFLIGHT'.

​

DATA d_ref TYPE REF TO data.

FIELD-SYMBOLS: <fs_wa> TYPE ANY,

<fs_comp> TYPE ANY.

​

START-OF-SELECTION.�

CREATE DATA d_ref TYPE (pa_dbtab).

ASSIGN d_ref->* TO <fs_wa>.

​

SELECT * FROM (pa_dbtab) INTO <fs_wa>.

DO.

ASSIGN COMPONENT sy-index

OF STRUCTURE <fs_wa> TO <fs_comp>.

IF sy-subrc NE 0. SKIP. EXIT. ENDIF.� WRITE <fs_comp>.

ENDDO.

ENDSELECT.

  1. Define input parameter for selection screen.
  2. Generic data object.
  3. Field symbols for record and record components.
  4. Dynamically generate the data object for storing the query result, and assign it to a field symbol.

​

  • Successively assign all structure components to a field symbol.
  • (reached the end ⇒ change the row and move to the next record)
  • Output component content.

228 of 243

12. Dynamic Programming

  • Field Symbols
  • Dynamic Access
  • Data References
  • Dynamic Determination of Object Properties
  • Code Construct with Dynamic Programming

228

© msg systems ag, 15.01.2013

229 of 243

12. Dynamic Programming�Determine properties of internal tables

229

© msg systems ag, 15.01.2013

DATA: no_of_lines TYPE i,

initial_lines TYPE i,

table_kind TYPE c.

DESCRIBE TABLE itab

LINES no_of_lines

OCCURS initial_lines

KIND table_kind.��* other variant:�no_of_lines = lines( itab ).

TYPE-POOL: sydes.

sydes_kind-undefined

sydes_kind-standard

sydes_kind-sorted

sydes_kind-hashed

table_kind

Number of rows in the internal table

Number of initial lines

Table kind

Constants for evaluating the return values

230 of 243

12. Dynamic Programming�RTTI – Run Time Type Information

230

© msg systems ag, 15.01.2013

Hierarchy of description classes:

CL_ABAP_TYPEDESCR

CL_ABAP_DATADESCR

CL_ABAP_OBJECTDESCR

CL_ABAP_COMPLEXDESCR

CL_ABAP_CLASSDESCR

CL_ABAP_ELEMDESCR

CL_ABAP_TABLEDESCR

CL_ABAP_INTFDESCR

CL_ABAP_REFDESCR

CL_ABAP_STRUCTDESCR

Rules

Determining the type attributes of a data object at runtime: :

  • Transfer the data object to the static method DESCRIBE_BY_DATA of class CL_ABAP_TYPEDESCR
  • Get the reference to the appropriate description object
  • Evaluate of the type attributes using the public attributes or methods of this description object

231 of 243

12. Dynamic Programming�Example for dynamic type description

231

© msg systems ag, 15.01.2013

...

DATA:

descr_ref TYPE REF TO cl_abap_structdescr,

wa_comp TYPE abap_compdescr.� ...

​

​

START-OF-SELECTION.

...� "get reference to type description object by widening cast:� descr_ref ?= cl_abap_typedescr=>describe_by_data( <fs_wa> ).

...

​

​

TOP-OF-PAGE.

LOOP AT descr_ref->components INTO wa_comp.

WRITE wa_comp-name.

ENDLOOP.

232 of 243

12. Dynamic Programming

  • Field Symbol
  • Dynamic Access
  • Data References
  • Dynamic Determination of Object Properties
  • Code Construct with Dynamic Programming

232

© msg systems ag, 15.01.2013

233 of 243

12. Dynamic Programming�Conventional Data Operations

233

© msg systems ag, 15.01.2013

DATA: itab TYPE TABLE OF structure,

wa TYPE structure.

​

READ TABLE itab INTO wa

WITH KEY age = 24.

​

IF sy-subrc = 0.

​

wa-wage = '1.900'.

MODIFY itab FROM wa.

​

ENDIF.

Index Name FName Age Wage

2 Maier Klaus 24 1.900

Index Name FName Age Wage

1 Huber Lotte 18 1.200

2 Maier Klaus 24 1.800

3 Berg Lisa 35 2.400

4 Reiß Tim 27 2.000

  • After reading a record, we have to check if the query was successful.
  • The changes made to the work area wa have to be written back to the internal table itab.

MODIFY itab FROM wa.

1.900

Changing a single, unique record

IF sy-subrc = 0.

ENDIF.

234 of 243

12. Dynamic Programming�Implementation with Field Symbols

234

© msg systems ag, 15.01.2013

DATA: itab TYPE TABLE OF structure.

FIELD-SYMBOLS: <fs> TYPE structure.

​

READ TABLE itab ASSIGNING <fs>

WITH KEY age = 24.

​

IF sy-subrc = 0.

​

<fs>-wage = '1.900'.

​

​

ENDIF.

​

Index Name FName Age Wage

1 Huber Lotte 18 1.200

2 Maier Klaus 24 1.800

3 Berg Lisa 35 2.400

4 Reiß Tim 27 2.000

  • After reading a record, we have to check if the query was successful.
  • The changes are made directly in the table.

1.900

Changing a single, unique record

IF sy-subrc = 0.

ENDIF.

<fs>

235 of 243

12. Dynamic Programming –�Conventional Data Operations

235

© msg systems ag, 15.01.2013

DATA: itab TYPE TABLE OF structure,

wa TYPE structure.

​

LOOP AT itab INTO wa

WHERE age = 24.

​

wa-wage = '1.900'.

​

MODIFY itab FROM wa.

​

ENDLOOP.

Index Name FName Age Wage

1 Huber Lotte 18 1.200

2 Maier Klaus 24 1.800

3 Berg Lisa 35 2.400

4 Reiß Tim 24 2.000

  • No verification needed, since the code is executed only when records are found.
  • The changes made to the work area wa have to be written back to the internal table itab.

Changing multiple, similar records

MODIFY itab FROM wa.

Index Name FName Age Wage

2 Maier Klaus 24 1.900

1.900

Index Name FName Age Wage

4 Reiß Tim 24 1.900

1.900

236 of 243

12. Dynamic Programming –�Implementation with Field Symbols

236

© msg systems ag, 15.01.2013

DATA: itab TYPE TABLE OF structure.

FIELD-SYMBOLS: <fs> TYPE structure.

​

LOOP AT itab ASSIGNING <fs>

WHERE age = 24.

​

<fs>-wage = '1.900'.

​

​

​

ENDLOOP.

Index Name FName Age Wage

1 Huber Lotte 18 1.200

2 Maier Klaus 24 1.800

3 Berg Lisa 35 2.400

4 Reiß Tim 24 1.900

  • No verification needed, since the code is executed only when records are found.
  • The changes are made directly in the table.

1.900

Changing multiple, similar records

<fs>

1.900

237 of 243

12. Dynamic Programming –�Conventional Data Operations

237

© msg systems ag, 15.01.2013

DATA: itab1 TYPE TABLE OF structure1,

wa1 TYPE structure1,

itab2 TYPE TABLE OF structure2,

wa2 TYPE structure2.

​

LOOP AT itab1 INTO wa1.

​

wa1-kz = 'U'.

MODIFY itab FROM wa1.

​

ENDLOOP.

​

LOOP AT itab2 INTO wa2.

​

wa2-kz = 'U'.

MODIFY itab FROM wa1.

​

​

ENDLOOP.

​

  • Each internal table has to be processed separately.
  • The changes made to the work area wa have to be written back to the internal tables.
  • Unmanageable number of data statements.
  • Great effort for extension.

Changing a common field in different internal tables

MODIFY itab FROM wa1.

MODIFY itab FROM wa2.

238 of 243

12. Dynamic Programming –�Implementation with Field Symbols

238

© msg systems ag, 15.01.2013

DATA: s_tab TYPE TABLE OF string,

s_wa TYPE string,

itab1 TYPE TABLE OF structure1,

itab2 TYPE TABLE OF structure2.

​

FIELD-SYMBOLS: <fst> TYPE ANY TABLE,

<fsw> TYPE ANY,

<fsk> TYPE ANY.

​

APPEND 'itab1' TO s_tab.

APPEND 'itab2' TO s_tab.

​

LOOP AT s_tab INTO s_wa.

​

UNASSIGN <fst>.

ASSIGN (s_wa) TO <fst>.

​

IF <fst> IS ASSIGNED.

​

​

ENDIF.

ENDLOOP.

  • 100% dynamic.
  • Easy to extend
  • Very complex!

Changing a common field in different internal tables

LOOP AT <fst> ASSIGNING <fsw>.

​

ASSIGN COMPONENT 'KZ'

OF STRUCTURE <fsw>

TO <fsk>.

​

IF <fsk> IS ASSIGNED.

<fsk> = 'U'.

ENDIF.�

ENDLOOP.

239 of 243

12. Dynamic Programming�Termination after accessing a field symbol which was not assigned

239

© msg systems ag, 15.01.2013

DATA: itab TYPE TABLE OF structure.

FIELD-SYMBOLS: <fs> TYPE structure.

​

READ TABLE itab ASSIGNING <fs>

WITH KEY age = 20.

​

IF sy-subrc = 0.

​

<fs>-wage = '1.400'.

​

ENDIF.

Index Name FName Age Wage

1 Huber Lotte 18 1.200

2 Maier Klaus 24 1.800

3 Berg Lisa 35 2.400

4 Reiß Tim 27 2.000

  • If no record is found, the field symbol points to nothing
  • The runtime environment responds the next usage of the field symbol with a short dump.
  • Check 'IS ASSIGNED'�or sy-subrc
  • RAISE EXCEPTION

Record not found!

IF <fs> IS ASSIGNED.

ENDIF.

<fs>

240 of 243

12. Dynamic Programming�Erroneous write access to pre-assigned field symbol

240

© msg systems ag, 15.01.2013

Index Name FName Age Wage

1 Huber Lotte 18 1.200

2 Maier Klaus 24 1.800

3 Berg Lisa 35 2.400

4 Reiß Tim 27 2.000

  • If no record is found, the field symbol continues to point to the last entry.
  • The next time you use it, the last value is overwritten.
  • UNASSIGN before each reading operation.

Record not found on the second query!

IF <fs> IS ASSIGNED.

ENDIF.

<fs>

DATA: itab TYPE TABLE OF structure.

FIELD-SYMBOLS: <fs> TYPE structure.

​

READ TABLE itab ASSIGNING <fs>

WITH KEY age = 24.

​

<fs>-wage = '1.900'.

​

READ TABLE itab ASSIGNING <fs>

WITH KEY age = 20.

"!!! <fs> still points onto Klaus

<fs>-wage = '1.400'.

1.400

1.900

241 of 243

12. Dynamic Programming�Summary

241

© msg systems ag, 15.01.2013

​

You should now be able to

  • Use field symbols and data references
  • Call methods dynamically
  • Determine properties of a data object at runtime

242 of 243

Bibliography

  • Horst Keller, Sascha Krüger: ABAP© Objects – ABAP Programmierung mit SAP NetWeaver, Galileo Press, Bonn (2006), ISBN 978-3-89842-358-8.
  • Roland Schwaiger: Schrödinger programmiert ABAP, Galileo Press, Bonn (2013), ISBN 978-3-8362-1858-0.
  • Horst Keller, Wolf Hagen Thümmel: Official ABAP™ Programming Guidelines, Galileo Press, Bonn (2009), ISBN 978-1-59229-290-5.
  • Andreas Wiegenstein, Markus Schumacher, Sebastian Schinzel, Frederik Weidemann: Sichere ABAP™-Programmierung, Galileo Press, Bonn (2009), ISBN 978-3-8362-1357-8.

242

© msg systems ag, 15.01.2013

243 of 243

243

© msg systems ag, 15.01.2013

Hubert Englmaier

​

Senior IT Consultant

Insurance

​

Telefon: +49 89 96101-4568

Hubert.Englmaier@msg-systems.com

​

www.msg-systems.com

Thank you for your attention!

www.msg-systems.com

Vielen Dank für Ihre Aufmerksamkeit