Sie sind auf Seite 1von 148

ABAP Objects

October,2005

Jayanth.C

© 2005 Intelligroup, Inc. Confidential and Proprietary


Topics to cover

 Why Object oriented ABAP?


 Class, objects, Methods & Constructor
 Inheritance, Polymorphism
 Events & Exceptions
 Real time usage of ABAP Objects
 Limitations

2
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Evolutions in ABAP as a programming
language
 In seventies ABAP stood for “AllgemeirBerichicts-
Aufbereitungs Prozessor”( General Report Preparation
Processor ).
 In mid eighties ABAP had developed into an interpreter
language which was a main component of the R/2
system and which could cope up with business
application programs.
 In early nineties, ABAP evolved as a 4th generation
programming language.

3
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Different approaches of Programming

Unstructured Programming.
Procedural Programming.
Object Oriented Programming.

4
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Unstructured Programming
report ysubdel.
DATA : sal type p decimals 2, Characteristics
itax type p decimals 2,
net_sal type p decimals 2 .
Consists of only one main program.
sal = 12000.
IF sal lt 5000 . The program stands for a sequence of
itax = 0.
ELSE.
commands which modify data that is
itax = sal * '0.01'. global throughout the whole program.
ENDIF.
net_sal = sal - itax.
write:/5 sal , itax , net_sal.
Disadvantages
sal = 3500.
IF sal lt 5000 .
itax = 0. Difficult to manage once the program
ELSE.
itax = sal * '0.01'. becomes large.
ENDIF.
net_sal = sal - itax. Same sequence of statements are
write:/5 sal , itax , net_sal. repeated at multiple places, if they are
needed at multiple locations.
5
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Procedural Programming
report ysubdel.
DATA : sal type p decimals 2 ,
itax type p decimals 2 ,
net_sal type p decimals 2.
A procedure call is used to invoke the
sal = 12000.
procedure.
PERFORM sub_calc_tax USING
sal itax net_sal. After the sequence is processed, flow
sal = 3500. of control proceeds right after the
PERFORM sub_calc_tax USING position where the call was made.
sal itax net_sal.

FORM sub_calc_tax USING


P_SAL P_ITAX P_NET_SAL.
IF p_sal lt 5000 .
p_itax = 0.
ELSE.
p_itax = sal * '0.01'.
ENDIF.
p_net_sal = p_sal - p_itax.
6
write:/5 sal , itax , net_sal.
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
ENDFORM.
Evolutions in ABAP as a programming
language
 At the turn of the new century, ABAP completed a new
stage in its evolution by ABAP/4 superseded by ABAP
objects.

Questions still unanswered:

 What are the implications by introducing ABAP objects?


How did it superseded ABAP which is still catering
customer needs anyways????
 Did ABAP objects made ABAP/4 obsolete?

7
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Implications of introduction of ABAP
Objects
 ABAP objects and ABAP are inextricably linked.
 Drift from a structural programming approach towards
Object oriented approach
 But to keep you comfortable, ABAP is still supported and
allows you to use object-oriented elements.

Questions Unanswered:
 Then why should I learn ABAP objects?
 Why don’t I use the classical approach?

8
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Are ABAP Objects mandatory?
Continue our Technical consultancy career in SAP with out
bottlenecks
Should be able to provide solutions to heterogeneous kinds of
client technical requirements related to
Program involving in Reuse available
multiple functional Standard/Custom classes
requirements in ABAP
Business Server Pages GUI Control Framework

Office Integration XML Transformations


BADI, Workflow Email, Shared Objects,
Persistent objects
Generic Programming New ABAP Editor, Code
Inspector, CATT
9
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Apart from the above…
 Simplicity

 Explicitness

 Maintainability

 Purified ABAP

 Scalability

 Adopt the universal approach for modern programming

10
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Orientation – What are Objects?

You interact with objects everyday


– A customer – Your car
– An order – The telephone

All objects contains state and behavior


– What they can do and what changes when they do

Software objects represent these as:


– Data ( like 4GL variables )
– Methods ( like 4GL procedures)
11
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
What's an Object and Class?
. Booch's object definition:
– “An object has state, behavior, and identity; the
structure and behavior of similar objects are defined
in their common class; the terms instance and object
are interchangeable.”
Ex: ICICI S.Acc#1111, ICICI S.Acc#1112, ICICI S.Acc#9999,
. Booch's class definition:
– “A class is a set of objects that share a common
structure and a common behavior.”
Ex: ICICI S.Acc.

12
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Some Classes & Their Objects
Maruthi 800 Raja’s Maruthi,
Prasad’s Maruthi,
Ramani’s Maruthi
Customer Steelcase, Coke, GE, BMS, Exxon,
Hitachi, Hospira

SalesOrder OR2643789, OR2643799


OR2643776, OR9999999

Cricket Team IndianTeam, Australian Team,


SrilankanTeam

Your Desktop PC IGA51097 etc.

13
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object-oriented Programming
“Object-oriented programming is a method of
implementation in which programs are organized as
cooperative collections of objects, each of which
represents an instance of some class...”
Grady Booch

14
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Behavior, State & Identity
Behavior:{Methods}
– “behavior is how an object acts and reacts, in terms of
its state changes and message passing.”
State:{Attributes}
– “... encompasses all of the (usually static) properties of
the object plus the (usually dynamic) values of each of
these properties.” .
Identity:{Key}
“... that property which distinguishes it from all other
objects.”

15
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object-oriented
Application Development
A way to design and build applications
– Objects bundle together data (state) and methods
(behavior)
– Objects facilitate separating definition from
implementation

Much more than just syntax


– You might have already done object-oriented
programming in the 4GL

16
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Sample Attributes & Methods
Class Attributes Methods
CricketTeam Captain, DoSingle,DoDouble
VC, WC, DoBowl,DoCatch
FB1,FB2,FB3 DoRunout,HitSix,
SP1,SP2,SUB Doplay,HitBowndary
ICICI S.A. Account Number, ATM_Transfer,
Balance, E_transfer, Withdraw,
CreditLimit Check_Credit_limit,
CheckBooks Issue_check_book,
Track_transactions
Production PO#,SSD,SED,AS Start_Production,End_produc
D,AED,Comp,CoO tion,Start_opr,Send_to_WS
ptn,Oper,Workce Etc
nter 17
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Basic Object-oriented Principles
Abstraction

Encapsulation

Hierarchies

18
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Abstraction
Public View of an Object

Abstraction is used to manage complexity


– Focus on the essential characteristics
– Eliminate the details
– Find commonalities among objects
Defines the public contract
– Public definition for users of the object
– The “Outside view”
– Independent of implementation

19
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Abstraction - Example

“What should an
Automobile
Object: Automobile object do?”

Start
Stop
Drive
PumpFuel

20
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Encapsulation
Hide Implementation Details

Encapsulation hides implementation


– Promotes modular software design – data and methods
together
– Data access always done through methods
– Often called “information hiding”
Provides two kinds of protection:
– State cannot be changed directly from outside
– Implementation can change without affecting users
of the object

21
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Encapsulation - Example
Object: Splendor
Implementation Outside View
EngineNum,
Gear#,
Fuel_MrtRd, Public
SpeedometrRd methods of
StartEngine(), Splendor class
StopEngine(),Cosu
mePetrol(),
Move_Wheel()
Start(),
Start(), Stop()
Stop() PumpFuel(),
PumpFuel(), Change_gear()
Change_gear() 22
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Encapsulation - Example continued
Object: Splendor
EngineNum, Hmm...
Gear#, I’d like to change
Fuel_MrtRd, Consume_petrol to
SpeedometrRd Consume_diesel
StartEngine(),StopE
ngine(),Consume_P
etrol(),
Move_Wheel()
Start(),
Stop() Consume_fuel() calls
Pump_Fuel(), Consume_Petrol( )
Change_gear()
23
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Encapsulation - Example continued
Object: Splendor

EngineNum,
Gear#, This change was easy
Fuel_MrtRd, because users of the
SpeedometrRd
object will not be
affected.
StartEngine(),
StopEngine(),Consu
me_Diesel(),
Move_Wheel())
Start(), Consume_fuel() calls
Stop() Consume_Diesel( )
Pump_Fuel(),
Change_gear()
24
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Hierarchies

Object Relationships
Define relationships between objects
– Objects defined in terms of other objects
– Allows state and behavior to be shared and
specialized as necessary
– Encourages code reuse

Two important hierarchy types:


– Inheritance
– Aggregation

25
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Hierarchies - Example

Automobile

is a is a is a

2-Wheeler 3-Wheeler 4-Wheeler

2-Wheerler,
3-Wheeler and
4-Wheerler
inherit from
Automobile 26
© 2005 Intelligroup, Inc. 2018/4/21
(Inheritance) Confidential and proprietary
Hierarchies - Example
Automobile
uses Engine
Automobile (Aggregation)

references

Engine

27
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Summary : Object-oriented Principles

Abstraction
– Break up complex problem
– Focus on public view, commonalities

Encapsulation
– Hide implementation details
– Package data and methods together

Hierarchies
– Build new objects by combining or extending other
objects

28
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
ABAP Object Oriented Programming

 Classes and objects are


used to model real world
entity.
 Methods inside the classes
perform the functions.
 Data used by the classes
are protected between them.

Class defined and


implemented

29
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
ABAP Object Oriented Programming

Defining a Referrence

Creating an Object

Calling a Method
Method implementation
30
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Comparison between Procedural and Object Oriented Programming

Features Procedure Oriented Object Oriented approach


approach

Emphasis Emphasis on tasks Emphasis on data

Modularization Programs are divided Programs are organized


into smaller programs into classes and objects
known as functions and the functionalities are
embedded into methods of
a class.
Data security Most of the functions Data can be hidden and
share global data cannot be accessed by
external sources.
Extensibility Relatively more time New data and functions
consuming to modify can be easily added
for extending existing whenever necessary 31
© 2005 Intelligroup, Inc. functionality. Confidential and proprietary 2018/4/21
Object Oriented Approach - key features

1. Better Programming Structure

2. Real world entity can be modeled very well

3.Stress on data security and access

4. Data encapsulation and abstraction

5. Reduction in code redundancy

32
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Summary-- Components of a Class

A Class basically contains the following:-

Attributes:- Any data,constants,types declared within a class form the


attribute of the class.

Methods:- Block of code, providing some functionality offered by the class.


Can be compared to function modules.

Events:- A mechanism set within a class which can help a class to trigger
methods of other class.

Interfaces:-Interfaces are independent structures that you can implement in


a class to extend the scope of that class.
33
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Oriented Design(OOD)

Five Major Steps


1. Identify the objects and their attributes
2. Identify the operations suffered by and required of each object
3. Establish the visibility of each object in relation to other objects
4. Establish the interface of each object
5. Implement each object

34
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Lets Design

35
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
DAY 2

© 2005 Intelligroup, Inc. Confidential and Proprietary


Classes
• Classes are templates for objects. Conversely, you
can say that the type of an object is the same as its
class.
• components of the class describe the state and
behavior of objects.
• Local and Global Classes: Classes in ABAP Objects
can be declared either globally or locally. You define
global classes and interfaces in the Class Builder
(Transaction SE24) in the ABAP Workbench. They are
stored centrally in class pools in the class library in
the R/3 Repository.

37
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes
• Local classes are defined within an ABAP program. Local
classes and interfaces can only be used in the program in
which they are defined.
• When you use a class in an ABAP program, the system first
searches for a local class with the specified name. If it does
not find one, it then looks for a global class.
• Apart from the visibility question, there is no difference
between using a global class and using a local class.
• Certain restrictions apply when you define the interface of a
global class, since the system must be able to guarantee that
any program using an object of a global class can recognize
the data type of each interface parameter.

38
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes
• Defining Local Classes:
• A complete class definition consists of a declaration
part and, if required, an implementation part.
The declaration part of a class <class>
CLASS <class> DEFINITION.
...
ENDCLASS.
• It contains the declaration for all components
(attributes, methods, events) of the class.
• The declaration part belongs to the global program
data.

39
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes
• If you declare methods in the declaration part of a
class, you must also write an implementation part
for it. This consists of a further statement block:
CLASS <class> IMPLEMENTATION.
...
ENDCLASS
• The implementation part of a local class is a
processing block. Subsequent coding that is not
itself part of a processing block is therefore not
accessible.

40
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Defining Local Classes
REPORT YSUBOOPS17 .
CLASS c1 DEFINITION.
PUBLIC SECTION.
Defined in the global area
data : w_num type i value 5. of a local program :-
methods : m1.
CLASS <class name>
ENDCLASS. DEFINITION.
CLASS c1 IMPLEMENTATION. …..
METHOD M1. ENDCLASS.
WRITE:/5 'I am M1 in C1'.
All the attributes ,
ENDMETHOD.
methods, events and
ENDCLASS. interfaces are declared here.
START-OF-SELECTION.
Cannot be declared inside a
DATA : oref1 TYPE REF TO c1 .
subroutine/function module.
CREATE OBJECT : oref1.
Class definition cannot be
write:/5 oref1->w_num.
nested.
CALL METHOD : oref1->m1 .

41
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Implementing Local Classes
REPORT YSUBOOPS17 .
CLASS c1 DEFINITION. Local class in a program is implemented as
follows:-
PUBLIC SECTION.
CLASS <class name>
data : w_num type i value 5. IMPLEMENTATION.
methods : m1. …..
ENDCLASS.
ENDCLASS.
CLASS c1 IMPLEMENTATION.
Methods used by the class are described here.
METHOD M1.
WRITE:/5 'I am M1 in C1'. A class can be implemented
ENDMETHOD. At the end of the program( like subroutines).
ENDCLASS.
After the class definition.
START-OF-SELECTION.
DATA : oref1 TYPE REF TO c1 . If the latter is adopted, one must then assign
subsequent non-declarative statements explicitly
CREATE OBJECT : oref1.
to a processing block, such as START-OF-
write:/5 oref1->w_num. SELECTION, so that they can be accessed.
CALL METHOD : oref1->m1 .

42
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Different places of implementing class
Class implemented at the end of Class implemented after Definition
the program

43
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes
Structure of a Class
The following statements define the structure of a
class:
• A class contains components
• Each component is assigned to a visibility section
• Classes implement methods

44
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Class Components
• All components are declared in the declaration part of the
class.
• When you define the class, each component is assigned to
one of the three visibility sections, which define the external
interface of the class.
• All of the components of a class are visible within the class.
• Instance components exist separately for each object in the
class
• static components exist only once for the whole class,
regardless of the number of instances.
• All components that you can declare in classes can also be
declared in interfaces

45
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Class Components
• Attributes:
• Attributes are internal data fields within a class that can have
any ABAP data type.
• The state of an object is determined by the contents of its
attributes.
• One kind of attribute is the reference variable. Reference
variables allow you to create and address objects.
• Instance Attributes: DATA
• Static Attributes : CLASS-DATA
• Static Attributes are accessible for the entire runtime of the
class.

46
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Class Components
• Methods
• Methods are internal procedures in a class that define the behavior of an object.
• They can access all of the attributes of a class. This allows them to change the
data content of an object.
• They are similar to function modules or procedures.
• The private attributes of a class can only be changed by methods in the same
class.
• In Definition Part
• Instance Methods: METHODS .
• Instance Methods can access all the attributes of a class and can trigger all the
events of a class.
• Static Methods : CLASS-METHODS . They can only access static attributes and
trigger static events.
• In implementation Part.
METHOD <meth>.
...
ENDMETHOD.

47
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Class Components
Special Methods:
• CONSTRUCTOR:
• Cannot call with CALL METHOD statement.
• Called automatically when you create an object
• CLASS_CONSTRUCTOR:
• Called when you first access the components of a class
Events:
• Objects or classes can use events to trigger event handler
methods in other objects or classes.
• When an event is triggered, any number of event handler
methods can be called.
• the handler determines the events to which it wants to react.
There does not have to be a handler method registered for
every event.

48
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Class Components
• The events of a class can be triggered in the methods of the
same class using the RAISE EVENT statement.
• The event handler methods can be of the same or a different
class.
• FOR EVENT <evt> OF <class>. Addition
• Events have a similar parameter interface to methods, but
only have output parameters.
• These parameters are passed by the trigger (RAISE EVENT
statement) to the event handler method, which receives them
as input parameters.
• The link between trigger and handler is established
dynamically in a program using the SET HANDLER statement.

49
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Class Components
• The trigger and handlers can be objects or classes, depending
on whether you have instance or static events and event
handler methods.
• When an event is triggered, the corresponding event handler
methods are executed in all registered handling classes.
• Instance Events: EVENTS keyword.
• An instance event can only be triggered in an instance
method.
• Static Events : CLASS-EVENTS
• All methods (instance and static methods) can trigger static
events.
• Static events are the only type of event that can be triggered
in a static method.

50
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Class Components
Types:
• You can define your own ABAP data types within a
class using the TYPES statement.
• Types are not instance-specific, and exist once only
for all of the objects in a class.
Constants:
• Constants are special static attributes.
• You declare them using the CONSTANTS statement.
• Constants are not instance-specific

51
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes : Visibility Sections
You can divide the declaration part of a class into up to three visibility
areas:
CLASS <class> DEFINITION.
PUBLIC SECTION.
...
PROTECTED SECTION.
...
PRIVATE SECTION.
...
ENDCLASS.
• They define the external interface of the class to its users
Encapsulation :
• The public components of global classes may not be changed once
you have released the class.
• As well as defining the visibility of an attribute, you can also protect
it from changes using the READ-ONLY addition.

52
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Sections of a There is no default visibility section in a class.

Class This sequence of visibility must be maintained


in a class

CLASS C1 A Class puts its components under


DEFINITION.
PUBLIC
three distinct sections:-
SECTION. Public Section:- Components placed
DATA: here form the external interface of the
METHODS: class – they are visible to all users of
EVENTS: the class as well as to methods within
PROTECTED
SECTION. the class and to methods of
DATA: subclasses*
METHODS: Protected Section:- Components
EVENTS: placed in protected section are visible
PRIVATE to the children of the class(subclass)
SECTION.
DATA:
as well as within the class
METHODS: Private Section:-Components
EVENTS: placed here are accessible by the
ENDCLASS. class itself. 53
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Who can use a class?
Subclass Externa
Class of the l user
itself class

REPORT YSUBOOPS17 . class c2 definition inheriting START-OF-SELECTION.


from c1.
CLASS c1 DEFINITION. DATA :
public section .
PUBLIC SECTION. oref1 TYPE REF TO c1 ,
methods : m2.
data : w_num type i value 5. oref2 type ref to c2 .
endclass.
methods m1. CREATE OBJECT : oref1.
ENDCLASS. write:/5 ‘As an user ' ,
class c2 implementation.
oref1->w_num.
method m2.
CLASS c1 IMPLEMENTATION. Call method oref1->m1.
write:/5 ‘From subclass' ,
method m1. w_num . Call method oref2->m2.
write:/5 ‘From class : ' , w_num. endmethod.
endmethod. endclass.
ENDCLASS.

54
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes

55
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classes
REPORT demo_class_counter .

CLASS counter DEFINITION.


PUBLIC SECTION.
METHODS: set IMPORTING value(set_value) TYPE i,
increment,
get EXPORTING value(get_value) TYPE i.
PRIVATE SECTION.
DATA count TYPE i.
ENDCLASS.

CLASS counter IMPLEMENTATION.


METHOD set.
count = set_value.
ENDMETHOD.
METHOD increment.
ADD 1 TO count.
ENDMETHOD.
METHOD get.
get_value = count.
ENDMETHOD.
ENDCLASS.

DATA number TYPE i VALUE 5.


DATA cnt TYPE REF TO counter.

START-OF-SELECTION.
CREATE OBJECT cnt.
CALL METHOD cnt->set EXPORTING set_value = number.
DO 3 TIMES.
CALL METHOD cnt->increment.
ENDDO.
CALL METHOD cnt->get IMPORTING get_value = number.
WRITE number.

56
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Two Additions in Local Class Definition

Addition 1 : CLASS class DEFINITION DEFERRED.

Used to refer to a class at some point in a code and the class is not
defined before the line.
CLASS C2 DEFINITION DEFERRED.
CLASS C1 DEFINITION. start-of-selection.

PUBLIC SECTION. data : obj1 type ref to C1.

DATA O2 TYPE REF TO C2. CREATE OBJECT obj1.

ENDCLASS. create object obj1->o2.

CLASS C2 DEFINITION. write:/5 obj1->o2->num .

public section.
data : num type i value 5.
ENDCLASS.

57
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Two Additions in Local Class Definition

Addition 2 : CLASS class DEFINITION LOAD


The compiler normally loads the description of a global class from
the class library the first time you use the class in your program .
However, if the first access to a global class in a program is to its
static components or in the definition of an event handler method ,
you must load it explicitly using the statement CLASS class
DEFINITION LOAD. This variant has no corresponding ENDCLASS
statement.

58
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
CREATE PUBLIC|PROTECTED|PRIVATE
ADDITIONS

Syntax : CLASS <classname> DEFINITION … [CREATE


PUBLIC|PROTECTED|PRIVATE]

CREATE PUBLIC addition is implicit in every class definition if the other CREATE
additions are not used. It defines the default state, that is, that every user can create
instances of the class.

Addition of CREATE PROTECTED means the class can only be instantiated by


itself or its subclass.

Addition of CREATE PRIVATE means the class can only instantiate itself or the
friends of the class can instantiate it.

59
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Handling
• Each object has a unique identity and its own attributes.
• Object References To access an object from an ABAP
program, you use object references. Object references are
pointers to objects. In ABAP, they are always contained in
reference variables.
• A reference variable that points to an object knows the
identity of that object. Users cannot access the identity of the
object directly.
• Reference variable can occur as a component of a structure
or internal table as well as on its own.
• There are two principal types of references: Class references
and interface references

60
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Handling
• ... TYPE REF TO <class>
Creating Objects
• CREATE OBJECT <cref>.
Addressing the Components of Objects:
• You can access the instance components of an object using
references in reference variables only.
• To access an attribute <attr>: <ref>-><attr>
• To call a method : CALL METHOD <ref>-><meth>
• You can access static components using the class name as
well as the reference variable.
• It is also possible to address the static components of a class
before an object has been created.

61
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Handling
• Addressing a static attribute <attr>: <class>=><attr>
• Calling a static method <meth>: CALL METHOD
<class>=><meth>
• Within a class, you can use the self-reference ME to access
the individual components:
• To access an attribute <attr> in the same class: ME-><attr>
• To call a method <meth> in the same class: CALL METHOD
ME-><meth>
• Self references allow an object to give other objects a
reference to it. You can also access attributes in methods
from within an object even if they are obscured by local
attributes of the method.

62
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Handling
• Assigning References
• When you assign a reference to a different reference
variable, their types must be either compatible or
convertible.
• <cref1> = <cref2>
• <cref1> and <cref2> refer to same class.
• <cref1> type ref to root class OBJECT.
• Inheritance & Interface situations.
• Class OBJECT is just a container. You cannot access
components of class with OBJECT reference

63
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Handling
• An object is in use by a program for as long as at
least one reference points to it, or at least one
method of the object is registered as an event
handler.
• Automatic garbage collection
• Object Names in debugger

64
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Object Handling

65
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
Declaring Methods :
• You can declare methods in the declaration part of a class or
in an interface.
To declare instance methods, use the following statement:
METHODS <meth>
IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
EXPORTING.. [VALUE(]<ei>[)] TYPE type [OPTIONAL]..
CHANGING.. [VALUE(]<ci>[)] TYPE type [OPTIONAL]..
RETURNING VALUE(<r>)
EXCEPTIONS.. <ei>..
and the appropriate additions.
To declare static methods, use the following statement:
CLASS-METHODS <meth>...
Both statements have the same syntax.

66
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
• The default way of passing a parameter in a method
is by reference.
• To pass a parameter by value, you must do so
explicitly using the VALUE addition.
• The return value (RETURNING parameter) must
always be passed explicitly as a value. If you use it,
you cannot use EXPORTING or CHANGING
parameters.
• You can use exception parameters (EXCEPTIONS) to
allow the user to react to error situations when the
method is executed.

67
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
Implementing Methods :
• METHOD <meth>.
...
ENDMETHOD.
• Static methods can work with only the static attributes of a
class.
Calling Methods :
• CALL METHOD <meth> EXPORTING... <ii> =.<f i>...
IMPORTING... <ei> =.<g i>...
CHANGING ... <ci> =.<f i>...
RECEIVING r=h
EXCEPTIONS... <ei> = rc i...

68
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Implementing Methods

All methods declared in the definition part of a class


should be implemented in the implementation section of
the class within the following block:-
METHOD <meth>.
...
ENDMETHOD.
One should not specify any interface parameters at the
time of implementation, since these are defined in the
method declaration.
The interface parameters of a method behave like
local variables within the method implementation. You
can define additional local variables within a method
using the DATA statement.

69
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Static Method

oLike any other class components , methods can


be static or instance.
oTo declare static methods, use the following
statement:
CLASS-METHODS <meth>...
oStatic methods can have import and ( export/
changing parameters ) or returning parameters . It
can also raise exceptions.
oStatic methods can only work with the static
attributes of your class. Instance methods can
work with both static and instance attributes.
oOne can call a static method using an object of
the class or directly using the class by class
component selector.

70
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
• Within the implementation part of a class, use
CALL METHOD <meth>...
• Visible instance & static methods can be called from outside
the class using
CALL METHOD <ref>-><meth>...
• Visible static methods can be called from outside the class
using
CALL METHOD <class>=><meth>...
where <class> is the name of the relevant class.
• You need not import the output parameters into your program
using the IMPORTING or RECEIVING addition. C

71
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
• If the interface of a method consists only of a single
IMPORTING parameter, you can use
CALL METHOD <method>( f).
The actual parameter <f> is passed to the input
parameters of the method.
• If the interface of a method consists only of
IMPORTING parameters, you can use
CALL METHOD <method>(....<ii> =.<f i>...).

72
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Dynamic Method Calls

Instance, self-referenced, and


static methods can all be called
dynamically; the class name for
static methods can also be
determined dynamically:
– oref->(method)
– me->(method)
– class=>(method)
– (class)=>method
– (class)=>(method)

73
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
Event Handler Methods :
• Event handler methods cannot be called using the CALL
METHOD statement. Instead, they are triggered using events.
• You define a method as an event handler method using the
addition
... FOR EVENT <evt> OF <cif>...
in the METHODS or CLASS-METHODS statement.
• The interface may only consist of IMPORTING parameters.
• Each IMPORTING parameter must be an EXPORTING
parameter of the event <evt>
• The attributes of the parameters are defined in the
declaration of the event <evt> (EVENTS statement) and are
adopted by the event handler method.

74
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
Constructors:
• Constructors are special methods that cannot be called using
CALL METHOD.
• They are called automatically by the system to set the starting
state of a new object or class.
• Constructors are methods with a predefined name.
• To use them, you must declare them explicitly in the class.
Instance constructor : You declare it in the public section as
follows:
METHODS CONSTRUCTOR
IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
EXCEPTIONS.. <ei>.
and implement it in the implementation section like any other
method.

75
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Declaring and Calling Methods
• The system calls the instance constructor once for each
instance of the class, directly after the object has been
created in the CREATE OBJECT statement.
• You pass the parameters to the constructor and handle the
exceptions in CREATE OBJECT stmt.
• static constructor :
• CLASS-METHODS CLASS_CONSTRUCTOR.
• The static constructor has no parameters.
• The system calls the static constructor once for each class,
before the class is accessed for the first time.
• The static constructor cannot therefore access the
components of its own class.

76
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Instance Constructor
Executed once for each instance.

Called automatically, immediately after the


CREATE OBJECT statement.

Can contain an interface with


IMPORTING parameters and
EXCEPTIONS , but cannot have any
EXPORTING/CHANGING/RETURNING
parameters .

The interfaces are defined using the same


syntax as for normal methods in the
METHODS statement. To transfer
parameters and handle exceptions, use the
EXPORTING and EXCEPTIONS additions
to the CREATE OBJECT statement .
77
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Static Constructor

REPORT YSUBOOPS2. Static methods, declared as CLASS-METHODS :


CLASS c1 DEFINITION . CLASS_CONSTRUCTOR in the public section of the class
PUBLIC SECTION. definition and are also implemented in the
CLASS-DATA : NUM TYPE I VALUE 5. implementation part.
CLASS-METHODS:CLASS_CONSTRUCTOR.
ENDCLASS. Has no interface parameters and cannot trigger
exceptions.
CLASS c1 IMPLEMENTATION.
METHOD CLASS_CONSTRUCTOR. Executed once in each program. It is called
WRITE:/5 'I am class automatically for the class before it is accessed for
constructor'. the first time - that is, before one of the following
ENDMETHOD.
ENDCLASS.
actions:
CREATE OBJECT obj from the class.
START-OF-SELECTION.
Call a static method : [CALL METHOD] class=>meth.
WRITE:/5 C1=>NUM.
Registering a static event handler method using SET
HANDLER class=>meth for obj.
Registering an event handler method for a static event
of the class class.
Addressing a static attribute with class=>a.
78
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Self-Reference

Internally, each method has an implicit self-


reference variable, the reserved word me
A method can access the components of its class
simply by their name; however,
 It may use me simply for clarity
 If a method declares a local variable with the
same name as one of the class components,
to avoid ambiguity it must use me to address
the variable originally belonging to the class.
 A method must use me to export a reference
to itself (that is, its object)

79
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
DAY 3

© 2005 Intelligroup, Inc. Confidential and Proprietary


Inheritance
• Inheritance allows you to derive a new class from an existing
class.
• CLASS <subclass> DEFINITION INHERITING FROM
<superclass>.
• The new class <subclass> inherits all of the components of
the existing class <superclass>.
• However, only the public and protected components of the
super class are visible in the subclass.
• You can declare private components in a subclass that have
the same names as private components of the super class.
Each class works with its own private components.

81
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Creating Subclass

Subclasses can be created from its


superclass using the syntax:-
CLASS <subclass> DEFINITION
INHERITING FROM <superclass>.
Subclass inherits all the public and protected
components of the superclass.
Superclass should not be declared as a
FINAL class.

82
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
• You can add new components to the subclass. This
allows you to turn the subclass into a specialized
version of the super class.
• A class can have more than one direct subclass, but
it may only have one direct super class. This is
called single inheritance.
• The root node of all inheritance trees in ABAP
Objects is the predefined empty class OBJECT.

83
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
• Redefining Methods: you can use the REDEFINITION addition
in the METHODS statement to redefine an inherited public or
protected instance method in a subclass and make its
function more specialized.
• The implementation of the redefinition in the subclass
obscures the original implementation in the super class.
• Any reference that points to an object of the subclass uses
the redefined method, even if the reference was defined with
reference to the superclass.
• This particularly applies to the self-reference ME->.
• Within a redefined method, you can use the pseudo reference
SUPER-> to access the obscured method.

84
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Modifying methods in subclass

To redefine a public/protected method of a


superclass in one of its subclasses, use the syntax
in the subclass definition:-
METHOD <method name> REDEFINITION

The interface and visibility of a method


cannot be changed while redefining it.

The method declaration and implementation in


the superclass is not affected when you redefine
the method in a subclass.

85
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
Abstract and Final Methods and Classes :
• An abstract method is defined in an abstract class and cannot
be implemented in that class.
• A final method cannot be redefined in a subclass.
References to Subclasses and Polymorphism:
• Reference variables defined with reference to a super class
can also contain references to any of its subclasses.
• A reference variable defined with reference to a super class or
an interface implemented by a super class can contain
references to instances of any of its subclasses.
• Reference variable defined with reference to OBJECT can
contain reference to any reference variable.
• CREATE OBJECT statement with type addition

86
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Abstract Methods and Classes

One cannot create an object from an abstract


class. Only subclasses can be derived from them.
CLASS <classname> DEFINITION ABSTRACT.

Abstract methods cannot be implemented in


the same class. Only the subclasses of that
class can implement it.

METHODS <method_name> ….ABSTRACT

Any class containing an abstract method has


to be an abstract class. All subsequent
subclasses that do not implement the method
must also be abstract. To implement an abstract
method in a subclass, one need to redefine this
subclass using the REDEFINITION addition.

87
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Final Methods and Classes

Final classes cannot have subclasses. Only the


class can be instantiated.

CLASS <classname> DEFINITION FINAL.

A final method cannot be redefined in


subclasses
METHODS <method_name> ….FINAL

88
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
Inheritance and Static Attributes
• In terms of inheritance, static attributes are not
assigned to a single class, but to a part of the
inheritance tree.
• When you address a static attribute that belongs to
part of an inheritance tree, you always address the
class in which the attribute is declared, irrespective
of the class you specify in the class selector.
• This is particularly important when you call the static
constructors of classes in inheritance.

89
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance and Static Attributes
CLASS c1 DEFINITION.
PUBLIC SECTION . Static attributes only exist
CLASS-DATA : num TYPE I VALUE 5 . once in each inheritance tree.
ENDCLASS. One can change them from
outside the class using the
CLASS c1 IMPLEMENTATION.
class component selector
ENDCLASS.
with any class name, or
within any class in which they
CLASS c2 DEFINITION INHERITING FROM
c1. are shared.
ENDCLASS.
They are visible in all
CLASS c2 IMPLEMENTATION.
classes in the inheritance
ENDCLASS. tree.

START-OF-SELECTION.
c2=>num = 7.
write:/5 c1=>num .

Output : 7
90
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
Inheritance and Constructors
• Every class has an Instance constructor called
CONSTRUCTOR.
• Instance constructors of the various classes in an inheritance
tree are fully independent of one another.
• You cannot redefine the instance constructor of a super class
in a subclass
• The instance constructor of a subclass has to ensure that the
instance constructors of all of its super classes are also
called.
• To do this, the instance constructor of each subclass must
contain a CALL METHOD SUPER->CONSTRUCTOR statement.

91
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
• Supplying values using CREATE OBJECT in inheritance
• Supplying values using
CALL METHOD SUPER->CONSTRUCTOR in inheritance.
• The instance constructor of a subclass is divided into two
parts by the CALL METHOD SUPER->CONSTRUCTOR
statement. In the statements before the call, the constructor
behaves like a static method
• In a constructor method, the methods of the subclasses of the
class are not visible. ( REDEFINITION not effective )
Static Constructors

92
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance and Instance Constructors

Superclasses and/or subclasses can have explicit constructors of their own.


Constructor of a subclass sometimes have to call the constructor of the superclass
using : CALL METHOD : SUPER->CONSTRUCTOR depending on the following:-

Case Description Necessity of calling


constructor of
superclass by
subclass
1 None of the superclass and subclass have Not required
explicit constructor.

2 Superclass have explicit constructor, but Not required


subclass does not have any explicit constructor.
3 Superclass does not have an explicit Required
constructor, but subclass have one.
4 Both the superclass and subclass have explicit Required
constructor
93
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Polymorphism via Inheritance

class c1 definition.
. . . . . . .
With inheritance, a reference variable
endclass.
defined with respect to a class may not only
class c1 implementation. point to instances of that but also to
. . . . . . instances of subclasses of the same. One
endclass. can even create subclass objects using a
reference variable typed with respect to a
class c2 definition inheriting from c1.
. . . . . . super class.
endclass.
class c2 implementation.
Polymorphism through inheritance can be
. . . . . . . achieved by playing with static and dynamic
endclass. type of a reference variable.
start-of-selection.
data : oref1 type ref to c1, Instances of a subclass may be used
oref11 type ref to c1, through the super class's interface. When
oref2 type ref to c2. this is done, a client can't access all
create object oref1 type c2 .
components defined in the subclass, only
create object oref2.
oref11 = oref2.
those inherited from the respective super
write:/5 oref1->num , class.
oref11->num .
94
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
Inheritance Overview:

95
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Inheritance
Inheritance and Reference Variables

96
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Interfaces
• Interfaces are independent structures that you can implement in a
class to extend the scope of that class.
• a universal point of contact.
• They provide one of the pillars of polymorphism, since they allow a
single method within an interface to behave differently in different
classes.
• Global & Local Interfaces
The definition of a local interface <intf> is enclosed in the
statements:
INTERFACE <intf>.
...
ENDINTERFACE.
• The definition contains the declaration for all components
(attributes, methods, events) of the interface.
• They automatically belong to the public section of the class in which
the interface is implemented.

97
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Defining Interfaces
report ysubdel .
interface i1. Can be declared globally or locally within a
data : num type i . program.
methods : meth1.
endinterface. Locally declared in the global portion of a program
using:-
class c1 definition.
public section. INTERFACE <intf>.
methods : meth1.
interfaces : i1. ...
endclass.
ENDINTERFACE.
class c1 implementation.
method : meth1. The definition contains the declaration for all
write:/5 'I am meth1 in c1'.
endmethod. components (attributes, methods, events) of the
interface.
method i1~meth1.
write:/5 'I am meth1 from i1'. Interfaces are included in the public section of a
endmethod. class.
endclass.
 Interfaces do not have an implementation part,
start-of-selection.
data : oref type ref to c1. create object oref. since their methods are implemented in the class that
write:/5 oref->i1~num. implements the interface.
call method oref->meth1.
call method oref->i1~meth1.
98
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Interfaces
• Interfaces do not have instances.
• To implement an interface in a class, use the statement
INTERFACES <intf>.
in the declaration part of the class.
• A component <icomp> of an interface <intf> can be
addressed as though it were a member of the class under the
name <intf~icomp>.
• Interface References
• Addressing Objects Using Interface References
Using the class reference variable <cref>:
• To access an attribute <attr>: <cref>-><intf~attr>
• To call a method <meth>: CALL METHOD <cref>-
><intf~meth>

99
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Interfaces
Using the interface reference variable <iref>:
• To access an attribute <attr>: < iref>-><attr>
• To call a method <meth>: CALL METHOD <iref>-><meth>
• Addressing a constant <const>: < intf>=><const> (Cannot use class
name).
• Addressing a static attribute
<attr>: < class>=><intf~attr>
• Calling a static method <meth>: CALL METHOD
<class>=><intf~meth>
(Cannot use Interface method ).
• casting operator (?= )
• <cref> ?= <iref>
For the casting to be successful, the object to which <iref> points
must be an object of the same class as the type of the class variable
<cref>.

100
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
DAY 4

© 2005 Intelligroup, Inc. Confidential and Proprietary


Triggering and Handling Events
• To trigger an event, a class must
Declare the event in its declaration part
Trigger the event in one of its methods
• EVENTS <evt> EXPORTING... VALUE(<ei>) TYPE type
[OPTIONAL]..
• To declare static events, use the following
statement:
CLASS-EVENTS <evt>...
Both statements have the same syntax.

102
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Triggering and Handling Events
• Triggering Events
• RAISE EVENT <evt> EXPORTING... <ei> = <fi>...
• The self-reference ME is automatically passed to the
implicit parameter SENDER.
• Handling Events
• Events are handled using special methods. To
handle an event, a method must
1. be defined as an event handler method for that
event
2. be registered at runtime for the event.

103
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Triggering and Handling Events
Declaring Event Handler Methods
• METHODS <meth> FOR EVENT <evt> OF <cif> IMPORTING..
<ei>..
• The event handler method does not have to use all of the
parameters passed in the RAISE EVENT statement.
• If you want the implicit parameter SENDER to be used as well,
you must list it in the interface.
Registering Event Handler Methods
• SET HANDLER... <hi>... [FOR]...
• Handler methods are executed in the order in which they were
registered.

104
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Triggering and Handling Events
Handler Table:

105
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
What is an Exception?

An exception is a situation that occurs during the execution of an


ABAP program, which renders a normal program continuation
pointless.
Exceptions can be detected at the time of program compilation or at
runtime.If the exception detected at runtime is not handled properly
by the program itself, we get a short dump and the execution
terminates.

106
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Classification of Exceptions

Exceptions of various kinds can be broadly classified as :-


Exceptions that can be handled.
Exceptions that cannot be handled.
Exceptions that can be handled indicate error situations in the runtime
environment or in the ABAP program, in the case of which the program
execution can be continued - by handling the exception in the ABAP
program - without the system reaching a critical condition. If such a
situation is not handled a runtime error will occur.
Exceptions that cannot be handled indicate critical error situations in
the runtime environment, which cannot be handled with/by ABAP means
and always cause a runtime error. Database space problem can be an
example of such category.

107
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Traditional Ways of Catching Runtime
Exceptions

Areas Brief Overview

In ABAP catch system-exceptions <exception_name> = <val>.


......
Endcatch.
If sy-subrc = <val> .
< exception handling statements>
Endif.
In function Creating exceptions for function module, raising them at
module appropriate points in the FM , assigning different sy-subrc
values for each exceptions at the time of the FM call and later
dealing with them.
In Methods Creating different exceptions at the time of declaring methods,
raising those exceptions within the method, assigning different
sy-subrc values at the time of method call and later dealing
with those values.

108
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
What is Class-based exception handling?

In Class-based exceptions handling approach, exceptions are generally


represented by objects of exception classes. There are pre-defined
exception classes for error situations in the runtime environment .
Users can also define own exception classes globally/locally, if required
and can raise them using RAISE EXCEPTION statement.
The runtime environment only causes exceptions that are based on pre-
defined classes, while in ABAP programs one can use raise pre-defined as
well as user-specific exception classes.
Class-based exceptions are handled using the control structure TRY ...
ENDTRY.
Class-based exceptions in procedures can be propagated to the caller in
the definition of the interface using the RAISING addition, if the exception is
not to be handled in the procedure.

109
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
TRY…CATCH…ENDTRY

Class-based exceptions are handled using TRY…CATCH…ENDTRY


block.

TRY. REPORT YSUBCLASS_EXCEPTION.

< code to be checked for


exception> DATA: i TYPE i VALUE 1.

CATCH cx1 ….cxn … [ into


ref]. START-OF-SELECTION.

< exception handling code>. TRY.


i = i / 0.
ENDTRY.
CATCH cx_sy_zerodivide.
write:/5 'Divide by zero caught'.
ENDTRY.

110
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – SAP
Exception Classes (2)
CX_STATIC_CHECK:
• For exceptions that have to be declared. This type should be chosen if you want to
make sure that this exception is always dealt with and if a local exception handler
has a chance to do something useful in an exception situation
• Corresponding exceptions must either be handled or forwarded explicitly with the
RAISING addition and this is checked at syntax check
CX_DYNAMIC_CHECK:
• For exceptions that do not have to be declared
• Exceptions must be handled or explicitly forwarded with the RAISING addition though
this is not checked at syntax check. Exceptions of this type are checked at runtime
only
• Useful for potential error situations that do not have to be handled, since the
program logic can more or less exclude them. Example: cx_sy_zerodivide
• Most of the CX_SY_ exceptions inherit from this class
CX_NO_CHECK:
• For exceptions that must not be declared (i.e. resource bottlenecks)
• Can be handled but not forwarded with RAISING. Otherwise will be propagated
through call chain automatically
• Not checked by syntax check or runtime processing
111
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
SAP Exception Classes

SAP provided exception-classes are derived from the specific class


CX_ROOT and have the prefix CX_.
Exception classes are normal classes with one limitation:-
Apart from the constructor, no methods can be defined for them. However,
CX_ROOT has some pre-defined methods available, which can then be
inherited by all exception classes.

Component Name (M)ethod/(A)ttribu Description


te

GET_TEXT M Returns a text description of the


exception

GET_SOURCE_POSITION M Returns the point at which the


exception occurred

TEXTID A Used to define different texts for


exceptions of a particular exception
class. Affects the result of the
method GET_TEXT. 112
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
SAP Exception Classes
Component Name (M)ethod/(A)ttrib Description
ute
PREVIOUS A If one exception is mapped to
another, this attribute stores the
original exception, which allows the
system to build a chain of
exceptions.
KERNEL_ERRID A Contains the name of the
appropriate runtime error if the
exception was triggered from the
kernel. If the exception was raised
using a RAISE EXCEPTION, this
attribute is initial.
TEXTID A Used to define different texts for
exceptions of a particular exception
class. Affects the result of the
method GET_TEXT.

113
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Nested Try…Catch…Endtry Blocks

TRY.
TRY.
Try block
CATCH cx_class INTO oref
Catch block
CATCH cx_class INTO oref
Try block Catch block

….
CLEANUP.
Cleanup block
ENDTRY.

CATCH cx_class INTO oref.


Catch block
CATCH cx_class INTO oref.
Catch block
….
… ….
CLEANUP.
Cleanup block

ENDTRY. 114
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
CLEANUP

Report ysubdel.
Used within a TRY…ENDTRY
data : w_num type i.
BLOCK , after all CATCH statements.
try.
try .
Each TRY block can contain
maximum of one CLEANUP area.
w_num = 5 / 0 .
cleanup. Used to release the external resources
write:/5 ‘In cleanup’.
when exception detected in a TRY
block is not handled within the block ,
endtry .
but is caught further up in the call
catch cx_sy_zerodivide. hierarchy.
write:/5 ‘Div. By zero!’.
Possible only in cases of nested TRY
endtry.
blocks.

In cleanup

Div. by zero! 115


© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Creating Local Exception Class in a program

To create a local exception class in a program and use it, follow the steps
outlined below.

Step 1 :- Create a subclass from global exception class in your program.

REPORT YSUBCLASS_EXCEPTION_3.
CLASS CX_SOME_EXCEPTION DEFINITION INHERITING FROM
CX_STATIC_CHECK.
public section.
methods : meth1.
ENDCLASS.

116
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Creating Local Exception Class in a program

Step 2 :- Implement methods of the subclass which will raise exception

CLASS CX_SOME_EXCEPTION IMPLEMENTATION.


method : meth1.
write:/5 'I am a method in exception'.
endmethod.
ENDCLASS.

Step 3 :- Define another class which will call the exception class.

CLASS SOME_CLASS DEFINITION.


PUBLIC SECTION.
METHODS: m1 raising cx_some_exception .
ENDCLASS.

117
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Creating Local Exception Class in a program

Step 4 :- Implement the method of the other class which will raise
exception of the locally declared exception class.

CLASS SOME_CLASS IMPLEMENTATION.


METHOD m1.
RAISE EXCEPTION TYPE CX_SOME_EXCEPTION.
ENDMETHOD.
ENDCLASS.

118
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Creating Local Exception Class in a program

Step 5 :- Create an object of the other class and call its method which
will raise the exception

DATA: c1 TYPE REF TO SOME_CLASS.


START-OF-SELECTION.
TRY.
CREATE OBJECT c1.
c1->m1( ).
CATCH CX_some_exception.
write:/5 'Exception caught'.
ENDTRY.

119
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Debug Mode

Exception has
occurred and has
been handled

120
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Debug Mode

Trigger point of
exception

Display Exception
Object
121
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Debug Mode

122
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (1)

Note Superclass
and class type
SE24

Enter class name Click Create

123
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (2)

Go to
Methods
Tab

Note the 2 attributes inherited from cx_root superclass


textid – Used to define different texts for exceptions of a particular
class. Affects the result of method get_text
previous – If one exception is mapped to another, this attribute can
store the original exception. If a runtime error occurs, the short dump
contains the texts belonging to all the exceptions in the chain
124
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (3)

Double click on
the constructor
method to view
code

Three methods are inherited from CX_ROOT


get_text, get_longtext – Returns the textual representation as a string,
according to the system language of the exception
get_source_position – Returns the program name, include name, and line
number reached where the exception was raised
A constructor method is automatically generated

125
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (4)

Click on
previous
object button
to return to
methods tab

Call to the constructor of superclasses is automatically


generated

126
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (5)

 First add an attribute to  Then return to the


the error class and methods tab and click on
activate the class the constructor again
127
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (6)

Click on
previous
object
button to
return to
methods tab

A line has been added to the constructor to initialize the new attribute.
This attribute will be available in the error object at runtime and will contain
the value that is passed to the constructor when the exception is raised
128
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (7)

Go to the Texts tab and add a text for the


exception ID.

129
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global Exception Class
(8)

The texts are stored in the Online Text Repository (OTR). The exception object contains
only a key that identifies the text (with system language)
The default text has the same name as the name of the exception class, in this case
ZCX_SOME_EXCEPTION.
You might wish to create an alternate text for the exception. That text can be entered
on this screen with a new exception ID and can be displayed by passing this value
to the parameter textid of the exception constructor.
130
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (9)

After performing a syntax check and


adding the texts to the OTR, return to the
Attributes tab
131
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Class-Based Exceptions – Creating a Global
Exception Class (10)

Don’t forget to activate the object!


Note that the text ID’s have been added to the attributes page as
class constants
132
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
DAY 8

133
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
5 Reasons – OO Programming is better than
Procedural Programming

 Data Encapsulation
 Instantiation
 Code Reuse
 Interfaces
 Events

134
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
3 Reasons – ABAP Objects is Better
ABAP

 ABAP Objects is more Explicit and Simpler to Use.


 ABAP Objects has a Stricter Syntax Check in Classes.
 ABAP Objects Provides Access to New ABAP Technology.

135
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
ABAP Objects is more Explicit and
Simpler to Use

ABAP Objects is much simpler and less error-prone


because :
 Classes contains attributes and methods.
 Objects are instances of Classes.
 Objects are addressed via references.
 Objects have clearly defined interfaces.

136
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Comparison between Procedural ABAP
and Object oriented ABAP
Procedural ABAP Object Oriented ABAP

 Contains Obsolete  Prohibits obsolete


Statements. statements and additions.
 Supports Overlapping and  Requires implicit syntax
and some specialized completions to be explicit.
objects.  Detecting and preventing
 Shows Implicit Behavior. incorrect data handling.
 Appears difficult to learn.

137
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Improve your Procedural Programming
using ABAP Objects

 Use methods as much as possible.


 Replace the use of Subroutines using static methods.
 Use function modules only when technically necessary.
 Disentangle procedural ABAP from ABAP Objects.
 Decouple screen programming from application
programming.
 Never uncheck the “Unicode checks active” checkbox.

138
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Stricter Syntax Check

139
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Stricter Syntax Check

140
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Internal Tables definition

141
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Database access

142
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Explicit Typing

143
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Data Handling

144
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Unicode Restrictions

145
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Unicode Restrictions

146
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
ABAP Objects Provides Access to
New ABAP Technology
 Frameworks for user dialogs such as SAP Control
Framework (CFW), BSP , Desktop Office Integration (DOI)
etc.
 Framework for persisting data in the database (Object
Services) and Shared Objects (area classes).
 Service classes such as CL_GUI_FRONTEND_SERVICES
for working with data at the presentation server.
 Language related classes such as Run Time Type
Services (RTTS), or CL_ABAP_EXPIMP subclasses for
extended IMPORT/EXPORT functionality.

147
© 2005 Intelligroup, Inc. Confidential and proprietary 2018/4/21
Thank You

© 2005 Intelligroup, Inc. Confidential and Proprietary

Das könnte Ihnen auch gefallen