You are on page 1of 28
Jargen Heymann, Horst Keller ABAP Objects - An Introduction |ABAP Object, the objectosented (00) extensin the ABAP language. avaiable wit reese 4.5/4 Release 48 adie inhsrtance. nested nlerisees.asd dynamic method tnvecaton. So far the response has weltake you though an inteducton w ADAP Obpcm ard give you acomprehensie exargle (The code fot the exanpe can be tesed cha debugged m DENG ABAP OBJECTS in is ekase $0.01 Nghe). ABAP Objects a nealy 160 percent upwari-compalbe extension! ABAF Pt Neluses a ul Seto! 00 ‘Estos. Wve lft aut some ebsoles language elements in the UO corte wrthinclsoes so fe not tral 100| percent compaible but youcan useobpcts nal cortex wiout any resretrs We crealed ABAP Objects because + The busines cbpet mpostony GOR) abwatly prezeried an OO view ofthe system o re outs and we wanted acomman programming mode! for outs are inate. + We wanted the poten bana of abject within R/2, neliding bata control afcampbsty. & belermeans lor ercapetsion sahinebiiy ad ruse anda kings bes or perkerc ard mew + We wanted seamless integration wit external ject models (COON and COREA|. + We nesded opel be the loundation fora new QUI pmgremnng mae (ke be competed in fast 10), Atthe begiring of he ABAP Object pric we face a fundamental question: Shout! ve add OO featves tuntg AGAP Eaguoge, svonia sompitel nem hngunge, orhigie as ening OO brgeage nts (eopledto negial 00 leatutes no he extng ABAP language t cteale ABAP Cbs or severe 2 woul mmaciaiey nbortal the other eatures ofthe Ri inecturtare uch ae ubke daiabaoe access, TP Mosilot cepablites, ae alldalabacebullerng Ghd ‘ontep ofa tinguage. This roulo in bm of germmtec cour. To supe these concep you Must have Your ‘wn compier mempreterard runtme. ruling ot mos: ene-sret languages, ‘+ Byintegratng the corceais of 0 langvages~as optosed b using a epecite 00 lanauage-—into ABP. we nore able © combine the bea! eatesplefrom these languages and adapt hem, wha nosdod ‘Our main design geat were: + Tose only proven 00 consents + __Toconplywiherteralciandarie whereverpoasble for exemple to alow mapping ts COM, conta, and UM) + To maui mach stoager ping (yea checking) than tacitonal ABAP, where ype speciation ie slmostaiwaye aptonal The Design Environment Jiirgen Heymann, Horst Keller ABAP Objects - An Introduction ABAP Objects, the object-oriented (0) extension to the ABAP language, is available with release 4,514.8, Release 4.6 adds inheritance, nested interfaces, and dynamic method Invocation. So far, the response has been very positive within and outside of SAP. In this article, as two of the developers of this new extension, we'll take you through an introduction to ABAP Objects and give you a comprehensive example (The code for the example can be tested and debugged in DEMO_ABAP_OBJECTS in R/3 release 4.6 or higher). ABAP Objects is a nearly 100 percent upward-compatible extension of ABAP that includes a full set of 00 features. We left out some obsolete language elements in the OO context within classes so it is not truly 100 percent compatible, but you can use objects in all contexts without any restrictions. We created ABAP Objects because’ + The business object repository (BOR) already presented an OO view of the system to the outside, and we wanted a common programming model for outside and inside. + We wanted the potential benefits of objects within R/3, including better control of complexity, a better means for encapsulation, extensibility, and reuse, and a language basis for patterns and frameworks. + We wanted seamless integration with external abject models (DCOM and CORBA). + We needed objects to be the foundation for a new GU! programming model (to be completed in release 5.0). At the beginning of the ABAP Objects project, we faced a fundamental question: Should we add 00 features to the existing ABAP language, Invent a completely new language, or integrate an existing OO language into R/3? We opted to integrate OO features into the existing ABAP language to create ABAP Objects for several reasons: + It meant we would immediately inherit all the other features of the R/3 infrastructure such as software logistics, portable database access, TP monitor capabilities, and all database buffering and scalability. + Certain features, such as persistence, transactions, events, and GUI frameworks, are hard to add on top of a language. This results in lots of generated code. To support these concepts, you must have your own compiler/ interpreter and runtime, ruling out most off-the-shelf languages. + Our target was a language for business applications. We wanted it to be simpler than Java and C++ and to leave out complex concepts lacking in benefits. + By integrating the concepts of OO languages--as opposed to using a specific OO language— into ABAP, we were able to combine the best concepts from these languages and adapt them, when heeded, to our specific needs. Our main design goals were: + To make ABAP Objects as simple as possible. + To use only proven OO concepts. + To comply with external standards whenever possible (for example, to allow mapping to COM, CORBA, and UML), + To require much stronger typing (type checking) than traditional ABAP, where type specification is almost always optional. The Design Environment When designing ABAP Objects, we faced some special R/3-specific challenges: 1 Estee vara: 2 2a mateapplentionthal ic massively configumble and extendable by five ‘© ASB anitempretve system, 20 there i nevera shukiownchaage-recomile-vestartoyce and pgletes must rote nindstedby the language. The change process mustos consitered anc Supoerec bycerain bnguage feaues (most resultng in some deiberale deviations tem the general stong HAE aE] You cannafemnimne thal deve pers alvmya can peat syrchroneum chal hemes mt hs ysis Some of ABAP Objects key design elements inciode sm tol straciums with methods esinCr) bute rew hind of ype + _ Reference Semantics for Objecs: ASAP is completely value-based. There are no ferences inthe language, anda HOVE always capa te valioa oven nth fils o/msie) Obpets onthe ster Pond can cnybe sceesordy wiernces (tere ave fo erbelied objects). Ths woulsinatchor separatinol values and picrences. An objet reference alas tas sterence semantics. The the onl place i ABAP whore sbects cre shored and never cope. Values (Be taditoral dala} are alvays copied. + Sing interince wit «seperate concept! interfaces: Here we otow a pathsimier b Java, Mest ‘mutpe niemance appicatons aw actualy nee cases, a ine bw extra capable of PURE Inhettance defnie¥ don! warn ihe compbxty thie teduces into fe lnawace vents are ineaices emir aoW tie oust n VEwal8ace. They are ouound methods thatcan nave parameters, The sa naural mede\for GUI applcations. We abo separated the event egistaton ib @ Separaie statement SET HANDLE) which gies you the ferdiy to dete alk ids cf Ppotgies of sender- ‘Shandlersonroctiors (1 Tn wt am) Ofcourse, A3AP Objects has is oun storage management (garbage cellecton) and ase cf ole Wan elaoe 45, the ABAP language @ prety mach complete with allabjectconpansnis, nfertance. and ested interfaces: Two maie areas of AEAP Objects are stl under deveopment Anew GUI programming ABAP Objects Basics ABAP Objects sneasd oa chncos. Chasen re pisces program toda that cathe object by deisng thet components, Typical objetconpersrisate atriuies lala) whith deacebe an abject nate, and matede {tunctons) wanén deserbe ancbjec'sbenavlor Object are etances of cesses, Many objects cal be ‘created fomore chs, buteach abect has teow siibutes ABAP Objects proves aset otnew sakaments hat defines clagees and hance abject, Thace statements ‘canbe used in anvkind of ABAP Eregram. (lsses, and thereto abject, consist cf atleast vo layers-ae inerasdan out! yer. The extn vebe yer of anobj! & made ip ofpiblecomporens Pubic componeniscanbe accesced ciecby all (mare and biman ebjects extemal point of cone! Prime comporeni are oni obb win abjets othe fame clos, The piblo secon tousiy contain tw elutes The slate of en ject genaraly Kept in Divateatrbvtes ard manpultedby puble mettoda. Ihe way an copet can ena fe own soncist cy. ‘Outcke ABAP Obes the only Imatarces in AAP ave ntaroes af wncle AGAP progmane.ich sa repors Imedil pool. or functin groups. Each fe aprogfam texecvied, apiogram isiance & mpletly crested ‘Rodi abo coctesan ABAP progam isianee, which conten the procedure, However, pened cal Shwayo use te sae one itctance. Such progian salanees Ive os Wig asthe cpplleaion program fuming nd eanratbs hancled spice Win AGAP Chpcte tis row poatbie to aepistly bands intarcas. Th iectarces of cnacss, ramely objects 1d expety nih ADAP stternent They hare a unsiue Henly (rcepencen ofthe cliute tues) + Extreme variability: R/3 is a meta-application that is massively configurable and extendable by five layers, + R/3 is an interpretive system, so there is never a shutdown-change-recompile-restart cycle. + Software development logistics allow for hundreds of developers to work on the same system parts, and logistics must not be hindered by the language. The change process must be considered and supported by certain language features (mostly resulting in some deliberate deviations from the general strong typing policy). You cannot assume that developers always can perform synchronous global changes in the system, ‘Some of ABAP Objects’ key design elements include: + Classes are not structures with methods (as in C++) but a new kind of type. + Reference Semantics for Objects: ABAP is completely value-based. There are no references in the language, and a MOVE always copies its values (even with field-symbols). Objects, on the other hand, can only be accessed by references (there are no embedded objects). This results in a clear separation of values and references. An object reference always has reference semantics. This is the only place in ABAP where objects are shared and never copied. Values (the traditional data) are always copied. + Single inheritance with a separate concept of interfaces: Here we follow a path similar to Java. Most multiple inheritance applications are actually interface cases, and the few extra capabilities of multiple inheritance definitely don't warrant the complexity this introduces into the language. + ABAP Objects integrates complex concepts, most notably events and dynamic method invocation. Events are introduced similarly to how they exist in Visual Basic. They are outbound methods that can have parameters. This is a natural model for GUI applications. We also separated the event registration into a separate statement (SET HANDLER), which gives you the flexibility to define all kinds of topologies of sender- to-handler connections (1:1, 4:n, n:1, n:m), + Of course, ABAP Objects has its own storage management (garbage collection) and a suite of tools such as the Class Builder, Class Browser, and debugger suppor. With release 4.6, the ABAP language is pretty much complete with all object components, inheritance, and nested interfaces. Two main areas of ABAP Objects are stil under development: A new GUI programming model and GUI design tool, and the Object Services framework that covers persistence, transaction control, and locking. These should be completed by release 5.0. ABAP Objects Basics ABAP Objects is based on classes. Classes are pieces of program code that describe abjects by defining their components. Typical object components are attributes (data), which describe an object's state, and methods (functions), which describe an object's behavior, Objects are instances of classes. Many objects can be created from one class, but each object has its own attributes. ABAP Objects provides a set of new statements that defines classes and handles objects. These statements can be used in any kind of ABAP program. Classes, and therefore objects, consist of at least two layers-an inner and an outer layer. The externally visible layer of an object is made up of public components. Public components can be accessed directly by all users and form an object's external point of contact. Private components are only visible within objects of the same class. The public section usually contains few attributes. The state of an object is generally kept in private attributes and manipulated by public methods. This way an object can ensure its ‘own consistency. Outside ABAP Objects, the only instances in ABAP are instances of whole ABAP programs such as reports, module pools, or function groups. Each time a program is executed, a program instance is implicitly created, which then runs in a separate ABAP process. Calling an external procedure (a subroutine or a function module) also creates an ABAP program instance, which contains the procedure, However, repeated calls always use the same one instance. Such program instances live as long as the application program is running and cannot be handled explicitly. With ABAP Objects, itis now possible to explicitly handle instances. The instances of classes, namely objects, are created explicitly with ABAP statements, They have a unique identity (independent of their attribute values) 2 and ar adreeaed by relerences. They Wve onl as ng asthey are needed Classes. Classes ate templates of objcts. You can elves define aekos weal nan ABAF proyean.o1 ‘lcbally in he clos lbrany using the Cass Buller el nthe ABAP Woxkbench. The class lorry ©parto the Bis reposiory Ces sary cheses am stored in special programs called cles pook. 8 cass pool S| Suiomateally gerom forsack glial cle that you crea wih the Claas Suite The Clase Sider cto Drograms ct nef System, Todetne ncalcksses ina ABAP progran, sich asa feportor&funetOn Group, you mest ype he corresponding staements manualy int the program. A lecal los b vieble onl inde the program in which & dated (lasses a defined be ween the CLASS and ENDCLASS ctalements & clas defniion consiss ofa. Component visibility. Gaon component muctbe declared mate of thee peso vebilty sections. All components declared i fre PUBLIC SECTION can bs accesoed by all chef ta Class, AU components ‘eclred in the PAO IEC IED SECTION canbe aotasced inte mathods ofthe class snd feubeleoees ee Inhertance).Al comeonenis declared in he PRIVATE SECTION can onlybe accessed inthe methods ofthe “Auttibutes: ate the inernaldata vols wie @cass. They con have any ABAP dala ype. We distrguish Denizen inatince stiles and site aries Instance atroates ar declarecby DATS and determine the Stale of an instance, You canrot wok wihinstarce atvbules witout creaing an col frst. State albus Slots atebutec form a daiacet hatin tared bythe what coos and allot is objects. You de nat ees 2 crea an copet wom wif ste cbs “methods: ave the lass procedues. They can access ai Class atubates, and can Heweiore change the site ofan aap. They hare aparaiaterirterace emir the interoce of froton module. They ean have famed IMPORTING. EXPORTING. ard CHANGING paramets.whichcanbs aptenaloreavired.anc can State methods ave dechied by CLASS-MIETHODS and car only access he tate atures of a cess. oBignaaneer CLiSeon Th obec crt PEL cana lames! Scenes ——<$—$ pe and are addressed by references. They live only as long as they are needed. Classes. Classes are templates for objects. You can either define a class locally in an ABAP program, or globally in the class library using the Class Builder tool in the ABAP Workbench, The class library is part of the Rv3 repository. Class library classes are stored in special programs called class pools. A class pool is automatically generated for each global class that you create with the Class Builder. The Class Builder also generates the coding frame thal defines the classes in the class pool. Global classes are visible to all ABAP programs of the R/3 System, To define local classes in an ABAP program, such as a report or a function group, you must type the corresponding statements manually into the program. A local class is visible only inside the program In which itis defined, Classes are defined between the CLASS and ENDCLASS statements. A class definition consists of a declaration part in which the components are defined and an implementation part, in which the methods are implemented. Component visibility. Each component must be declared in one of three possible visibility sections. All components declared in the PUBLIC SECTION can be accessed by all clients of the class, All components declared in the PROTECTED SECTION can be accessed in the methods of the class and its subclasses (see inheritance). All components declared in the PRIVATE SECTION can only be accessed in the methods of the class. The public section forms the outer layer, or external interface, of the class. ‘The protected and the private sections form the inner layer. Their components cannot be accessed by external users. Class components. Possible class components are attributes, methods and events. Events will be explained later in this article, “Attributes: are the intemal data variables within a class. They can have any ABAP data type. We distinguish between instance attributes and static attributes. Instance attributes are declared by DATA and determine the state of an instance. You cannot work with instance attributes without creating an object first, Static attributes are declared by CLASS-DATA and determine the state of a class, which in a way applies to all instances. Static attributes form a data set that is shared by the whole class and all of its objects. You do not need to create an object to work with static attributes. *Methods: are the class’ procedures. They can access all class attributes, and can therefore change the state of an object. They have a parameter interface similar to the interface of function modules. They can have named IMPORTING, EXPORTING, and CHANGING parameters, which can be optional or required and can be passed elther by reference or by value. As with attributes, we distinguish between instance methods and static methods. Instance methods are declared by METHODS and can access all the alfributes of a class. Static methods are declared by CLASS-METHODS and can only access the static attributes of a class, CLASS vessel DEFINITION, PUBLIC SECTION. METHODS: constructor, drive IMPORTING speed_up TYPE i, get_id RETURNING value(id) TYPE i, PROTECTED SECTION. DATA: speed TYPE i, max_speed TYPE i VALUE 100, PRIVATE SECTION. CLASS-DATA object_count TYPE i. DATA id TYPE i, ENDCLASS. CLASS vessel IMPLEMENTATION METHOD constructor. ‘object_count = object_count +1 Lita t defines a cass vessel The comporents of class vessel are the atrbutes sued max speed. Fue | stows now te case vessels composed by fs sbi Sections. Usthod implementation, Each mathe cechad in the declamton arto aches mist be implemented in ts imettod, ut ABAP Objects does use srcier SymlX im some paces m avOH spools Yealutes MetnOGs may ‘confain decorations of cal data and data be. Constructors. Implcity, each cass has an instance constcor method with he reserved name constructor theculed each tine you creat an object (netance) wih fhe CAGATE ODJEC Tcinlomen, whe the acs ‘Constracot executed exact) once Defoe you ist aovess a Cass. The couswobva ae cimajspiecenL However, b mplementa constrico you mustdsclaw ft axpleely wth the METHODS or CLsSS-METHODS Stalements An nstarce consinctorcan have INPORTING parameie's ard exceptions. You mist pass ll Objects and object references Obpcta ae ictances atcheces From the ucat'poiat af vi, there i almost no dite ice between ciseting Objects based on glbal casees and creating therm on oval class, ‘The stalementsforciaing and handing ebects are exact ihe same forooth Ypesol cscs. Vebity max_speed. speed = max_speed. ENDIF. ENDMETHOD. METHOD get id me->id, ENDMETHOD. ENDCLASS, Listing 1 defines a class vessel. The components of class vessel are the altributes speed, max_speed, object_count, and id, and the methods constructor, drive, and get_id, Figure 1 shows how the class vessel is composed by its visibility sections. Allusers Class VESSEL Public Private components, components constructor: ‘object_eount drive id getiad Metiod implementations Protected components speed, max-speed Subclasses of VESSEL Method implementation. Each method declared in the deciaration part of a class must be implemented in its implementation part. Each implementation is enclosed between the METHOD and ENDMETHOD statements, You can use almost all ABAP statements available in subroutines or function modules to implement the method, but ABAP Objects does use a stricter syntax in some places to avoid obsolete features. Methods may contain declarations of local data and data type. Constructors. Implicitly, each class has an instance constructor method with the reserved name constructor and a static constructor method with the reserved name class_constructor. The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statement, while the class constructor is executed exactly once before you first access a class. The constructors are always present. However, to implement a constructor you must declare it explicitly with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING parameters and exceptions, You must pass all non-optional parameters when creating an object. Static constructors have no parameters. Objects and object references, Objects are instances of classes. From the user's point of view, there is. almost no difference between creating objects based on global classes and creating them on local classes. The statements for creating and handling objects are exactly the same for both types of classes. Visibility distinguishes between global and local classes. While any program can create objects from classes in the class library, only the defining program can create objects from its own local classes. Reference variables. Objects live in the internal session of an ABAP program and are accessed only via reference variables, Object reference variables contain references (pointers) to objects and must be declared before creating an abject and accessing its components. 4 To dicta a eleence varabe, you use te new data ype AEF TO cso. LKe otter varebie,reterence ‘arenes car be compenen's oj sucturesor neal tes. Yeu intiiae arelcrence Yara wih the CCLERE tttamart: The intial vow ofa mibrance vaio a mbrence that cose not pent anode Instances. Cree you have declared reference variable ors{with he type ofa class. you can creat a cess FRulanee lise he Sniement CREATE OA.ECT rel whichereaiea sn tctace af the cle wih fe pe of obect You can crate any nunbero! KeBceTO! the same Cs i aprogram. Those instances ave Uy -ndepandest of ach other are they have heitown deny ard atroules wih the pregiam You car ecsign 'Sherercesbetveen reference varables using he MOVE statementorpacs em as barometers. ASAP Gbps rterance Yarebles are aways peste Inthe sans Mat they san ory cantin point object= thal tothe nt ace gent the reference varablesdecbrakon hype. thatchock is motpecebe eatcal, ou ean eastieterence vabbs at un ie ee Wate vec Pore, ‘pects ere shown n ie same format (Gctlassname>)ac fe coflans of eeence VArEDES the ABAF DebugperTheoe nan canatbe uced cecil nthe program. Garbage colleston. An beet & inuse as long as there Sat kast one releesce poining it When there To declare a reference variable, you use the new data type REF TO class. Like other variables, reference variables can be components of structures or intemal tables. You initialize a reference variable with the CLEAR statement. The intial value of a reference variable is a reference that does not point to an object. Instances. Once you have dectared a reference variable oref with the type of a class, you can create a class instance. Use the statement CREATE OBJECT oref, which creates an instance of the class with the type of oref and places a reference to the new instance into oref. Each CREATE OBJECT statement creates a new object. You can create any number of instances of the same class in a program. Those instances are fully independent of each other, and they have their own identity and attributes within the program. You can assign references between reference variables using the MOVE statement or pass them as parameters. ABAP Objects’ reference variables are always type-safe in the sense that they can only contain pointers to objects that fit to the interface given by the reference variable's declaration type, If that check is not possible statically, you can cast reference variables at run time. DATA: vessel! TYPE REF TO vessel, vessel2 TYPE REF TO vessel DATA vessel_id TYPE i. CREATE OBJECT: vesselt, vessel2, ‘CALL METHOD: vesselt->arive( 50 ), vessel2->adrive( 80 ) /essol1->get_id{ ). WRITE: /'Vessel ID is, vessol_id sessel2->get_{d{ ). WRITE: /'Vessel ID is, vessel_id Listing 2 declares two reference variables vessel1 and vessel2 and creates two instances of class vessel with the two reference variables pointing to them. Methods of the objects are then called Figure 2 shows the two reference variables,each pointing to an instance of class vessel. The names of the objects are shown in the same format (id) as the contents of reference variables in the ABAP Debugger. These names cannot be used directly in the program. Intemal session of an ABAP Programm i< VESSEL VESSELI J VESSEL? Garbage collection. An object is in use as long as there is at least one reference pointing to it. When there are no more references pointing to an object, the memory space occupled by that object can be released, 5 ABAP Objects provides agnibage calector. which ensures that the memory iscolkcied aulomateally Accessing the components of objects. To access an itsintce component fom outste the defining class fan tee dopel eongenénlerbser 5, whch conten Ie sea fy feremre} is te cores pent eee ‘Simi, the class componeet ebeclor zs combines the class win the component name when you access & staie component To ascass atrbuees, you wie oles for netance atu and Sass=satl oy Sub atubuRs, Toate inetfod, you wite CALL METHOD ofet->meth or an nstance methodand CALL METHOD ctse=>meth fora Stabe methoe. CALL UETHOD has inca tle sare synax as CALL FLNGTION. but ABAP Object adic ‘eSonel methogs. These are characieszedby the fact et beates IMPORTING parameter they have ‘actly one RETUBNING parainew. Ths ba advantage beceuse they cal be used Ike ah oor vara “ect) meetin eyprecsons Insead ol enterng a vanable rame, fou simpy wre oreL>meth.) oF ‘lass=>meth,)speciing the fequred [MPORTING parameters wihn the parentheses. Dung the execution Insce method; components of he same clos canbe adored rectly by tir names; where the compiler preperds he oe eteence ME inpicty. Only ncpectalcases~ ol camp wien an atibut fs hidden bya Dealdata cbect orparameter vith he came name-are you requred fuse jot he ME->at notation to ‘olkily selec the atrb ue (see an example in he construct in Listing 3). ME can akobe toed whena Inheritance. inkertance alws you f darko new chenes trom an isting ane. The sow clase hoi ail Siperease # subctes ruses Ine coce of cupercacsutanl the pubic ana prowl components of te Supercass ae vb it tb subcasces. You can define addtenalcarponsnisin be subcbss, making Mere ‘ony a age stpercess. Aspecalking cf mulipe Iniertance le AUP Objects © provEeaDy Iniracze ‘which we wi gee chorty When a subclass inherits trom = sypescss thatisitcel'@ subclass of anotherclass, the classes imobed fman nhetiance fee. which becomes more epecialited moving fom top Dbetiam. The components ofa [eS iene ten ent Pug. sectoN, tattoos case ABAP Objects provides a garbage collector, which ensures that the memory is collected automatically Accessing the components of objects. To access an instance component from outside the defining class, you use the object component selector ->, which combines the object (reference) with the component name. Similarly, the class component selector => combines the class with the component name when you access a static component. To access attributes, you write oref->attr for instance attributes and class=>attr for static attributes. To call ‘a method, you write CALL METHOD oref->meth for an instance method and CALL METHOD. class=>meth for a static method. CALL METHOD has almost the same syntax as CALL FUNCTION, but ABAP Objects adds functional methods. These are characterized by the fact that besides IMPORTING. parameters, they have exactly one RETURNING parameter, This is an advantage because they can be Used like an ordinary variable directly in certain expressions. Instead of entering a variable name, you simply write oref->meth(...) or class=>meth\...) specifying the required IMPORTING parameters within the parentheses. During the execution of the expression, the method is evaluated, and the value of the RETURNING parameter is used in the expression. Inside methods, components of the same class can be addressed directly by their names, where the compiler prepends the self reference ME implicitly. Only in special cases~ for example when an attribute is hidden by a local data object or parameter with the same name-are you required to use just the ME- >attr notation to explicitly select the attribute (see an example in the constructor in Listing 3). ME can also be used when a method wants to pass a reference that points to its own object. Inheritance. Inheritance allows you to derive new classes from an existing one. The new class inherits all components of the existing class and is known as the subclass. The existing class is known as the superclass. A subclass reuses the code of its superclass, but only the public and protected components of the superclass are visible in its subclasses. You can define additional components in the subclass, aking it more specialized than the superclass. A subclass itself can become a superclass of additional new classes. This allows you to introduce several degrees of specialization. Subclasses. To define a subclass, you use the INHERITING FROM clause in the CLASS statement of the declaration part. ABAP Objects supports single inheritance. Classes can have several direct subclasses, but only a single superclass. A special kind of multiple inheritance in ABAP Objects is provided by interfaces (which we will get to shortly. ‘When a subclass inherits from a superclass that is itself a subclass of another class, the classes involved form an inheritance tree, which becomes more specialized moving from top to bottom. The components ofa superclass are passed on to all subclasses within the tree. The implicit root node of all ABAP Objects Inheritance trees is the predefined class OBJECT. CLASS ship DEFINITION INHERITING FROM vessel. PUBLIC SECTION. DATA name TYPE string READ-ONLY. METHODS: constructor IMPORTING name TYPE string, write, drive REDEFINITION, ENDCLASS, CLASS ship IMPLEMENTATION. METHOD constructor. CALL METHOD super->consiructor. max_speed = 30. me->name = name. ENDMETHOD. METHOD write DATA id. id = me->get id). WRITE: / name, 6 Petes ining 92 eiicls ship ide ve from sipercine vemnel The nbclwe sip epecialices in super lems; Dyadcing a new atribui Rama anda new methed wits Furthermore class SNE fae fe own consturtor and redefine the meted civ Aedefintion. in sclasses, you can meke th puble and protected inate methods oll preceding Stipercasses specie by redetinng them Using the REDEEINITION classe of he METHODS sstoment You sannot change to inorace of 2 fadefined meshed methadaae marsh fern ander he sane rome. Wihiva redefined method, you cen use the porwerelerence SUPER te fsczess the methed wih he sare name in the siperclase lb alvaysa geod dea tcallte supereeSS ‘nethod thot yo are rade bstor spacilcing you deine an instance construct in a subclass. you must call the isiace construc ofthe superclass by using CALL METHOD super-sconstuctor nits melementation. Before the cal. he cube ass censtuco” Sonaves Ikea sate method itean aozeae only ate atibutes in tha pa ofthe eoncinctor Déoeths salt sSipetcass isconpetel hitalzedbstoe the subctss accesses fs atrbules. Abstract and final ABAP Objects alsa provides ABSTHACT and FINAL cluoes Ike other OO languages Wah the ABSTAACTand FNAL clauses forthe METHODS and CLASS siemens youcandefne cbetact Clans but Haxpecte«aubclaas i provide > (qpecmined implementation When = class haz one or more ftstect methods, he Gass ae woke becomes sbeltct or nconplte, Thereore, you cannotorale Sbstact cs ebpcts. The FINAL clause alts you reste! mhertance. Final methods cao! be redefined ina subcines snd fralclnases earns hav ay ither sabclaases Polymorphism. Polymohiom isa very impotiastOO concept Irheriance provides one mears of polmorham li tac! = heat sest han'on sonsier using abject vs a rataens arabe: Poiymemphnm ny subcmass ofthat class vessel suct es mo an ntance oT sip oF Goal. Since a suDsts has al eas ale component ofal ie supetclasers, You an access all he components of vaste in any subcbes. 6 usd & However, the most important part of polymorphism in terms o! inheritance isthe methods. Cone the ‘exanpk above: A cass sh © ihefied rom clas vessel and hs redefined the method die. When we now ite apeiner'o an intance of aha ine rference varable af ype REE-TO wassel and we cathe method ‘The general ule: When cating & mettod, the most speciued redtinitn (na subclass) gets eae. TH ‘netiod can then dest cal te supercacs iplemertaten. Thee. wth hbertence a methedcallgees ctr own 98 pecs sn your own cede mit cal the implementations o hi method upwards. In ABAP Obpets you ar only alowed to calla methossdinct predecemser mplrme maton. You con any go ene bvel ‘ep with CALL METHOD SUPER-om and you can ony call your own method end nototber method o! your Stpatcase (Theos estielone ate not for echnical moaone bute Que the oars! ABAP Object tate Droper use o inhertance “is vesser, id, ‘and has speed’, speed. ENDMETHOD. METHOD drive. speed = speed + speed_up. IF speed > max_speed. speed = 0. ENDIF. ENDMETHOD. ENDCLASS. Listing 3 Statements for deriving a subclass. max_speec In Listing 3, a subclass ship is derived from superclass vessel. The subclass ship specializes its superclass, by adding a new attribute name and a new method write. Furthermore, class ship has its own constructor and redefines the method drive. Redefinition. In subclasses, you can make the public and protected instance methods of all preceding superclasses specialized by redefining them using the REDEFINITION clause of the METHODS statement. You cannot change the interface of a redefined method. Redefined methods are merely implemented differently under the same name. Within a redefined method, you can use the pseudoreference SUPER to access the method with the same name in the superclass, It is always a good idea to call the superclass method that you are redefining before specializing it. Ifyou define an instance constructor in a subclass, you must call the instance constructor of the superclass by using CALL METHOD super->constructor in its implementation. Before the call, the subclass constructor behaves like a static method. It can access only static attributes in that part of the constructor. After the call, it behaves like an instance method and can also access instance attributes. This is to ensure that the superclass is completely initialized before the subclass accesses its attributes. Abstract and final. ABAP Objects also provides ABSTRACT and FINAL clauses like other OO languages. With the ABSTRACT and FINAL clauses for the METHODS and CLASS statements, you can define abstract and final methods or classes. When a method is declared abstract, it doesn't have an implementation in this class, but it expects a subclass to provide its (specialized) implementation. When a class has one or more abstract methods, the class as a whole becomes abstract or incomplete. Therefore, you cannot create abstract class objects. The FINAL clause allows you to restrict inheritance. Final methods cannot be redefined in a subclass, and final classes cannot have any further subclasses. Polymorphism. Polymorphism is a very important OO concept. Inheritance provides one means of polymorphism. Its effect is best seen when we consider using objects via a reference variable. Polymorphism means that a reference variable with the type REF TO vessel can always contain references to instances of any subclass of that class vessel, such as to an instance of ship or boat, Since a subclass has at least all the components of al its superclasses, you can access all the components of vessel in any subclass. By using a higher level reference, you simply ignore the components added in subclasses. However, the most important part of polymorphism in terms of inheritance is the methods. Consider the example above: A class ship is inherited from class vessel and has redefined the method drive, When we now have a pointer to an instance of ship in a reference variable of type REF TO vessel, and we call the method drive, the drive method of the class ship is executed even though the reference to that instance is of type REF TO vessel. ‘The general rule is: When calling a method, the most specialized redefinition (in a subclass) gets called. This method can then directly call its superclass implementation. Thus, with inheritance, a method call goes as far down as possible, and your own code must call the implementations of this method upwards. In ABAP Objects, you are only allowed to call a method's direct predecessor implementation, You can only go one level up with CALL METHOD SUPER->m, and you can only call your own method and not other methods of your superclass. (These restrictions are not for technical reasons but to guide the users of ABAP Objects towards proper use of inheritance.) 7 Aelerence varies cas ainays ld iference to cubcles instances. n paricub, the root ctass OBJECT ‘can od relerences any object Using the normal metho cal or si-bulesezess robaton, you can only [access componanis of he ches tha was teal lo dafine he ference varebie Ory dynam ruck alu the waerto access statealy unenoun methods For oxompl. i subctaos ah had an adatonal method ine Jou coul sotcalltutcall though e reerence al pe REF TO votes! Eul you could calla uring the ‘Synaral ‘hy TPEREE TO oe lensare couesratp E1PORTNG mane = tani: [CALL METHOD aint 20), Ey TO ree, [cet MteTHOD esac lear serio ati-oate Listing ddachas tue reference varabies one ol tpe seazal aecone of ype chp. Achasatip bjee! ic ‘erkbit Inboltcasse. te method de that a decled i clas veoselw clad, But youcannol Gat the ‘nethod wrte wth reference vareble vessel ‘Te motet cating of metoas fat are recatnes in sclasoes mane fat weh the superclass narace, a method cal accesses dflerert method implemertatons in difetent stbclasces. This hasan important Sheayoco mere than the supercasobut never ave anything way Interfaces. The pibic componente ofa clas define the externa pohtot contactor he class They define the semanic interface spacti fo hin clans Aran llcon. Customer class woul! have » Customs However there ar many asote when we wantanctherkind of palmomphism one that is independent of ‘The AmbiveManagerclico wants t define wht # needs inonfero archive a cas in © epecilinesoce and nen access aldtferen cawaes unioimy though inetnerlce, noes tae whatepectio cas t Sscueseing. itary cares about the arching sopect All clesees that want to be achved must mpement te IF Archie inriece-Inthe same way.a Wokfilanagerchss would define an fF Workle inface, and The general concept of ins faces i this: An ineface i @ sapmiate Inguage const that ellowed to Jeti components (suchas iste pubis action ol a oes) but without implomentaton. Classes 2 impkiventove or move ineitacesin the puble Sector, Weteby extenny ne socton ‘eteerore only show ttoce corponsnts alae Gefned inthe eda, egartizea of te inp meng flee. When aces mpkirets a eae, we cangsta ewes Wary mplmenled Merace by wy of Interfaces in ABAP Objects. Lie chases, youcan cine intrfacas label inthe chs Horry or ely wikis an ADAP program. Ini feces. defined between the INTERFACE axa ENON TERFACE attement ‘They cat contin te some compunetis as cusses. An erace’s methods a ot plemented lathe inerace se, but mustbe mpbmentd ie te Gasses thatinplement the interface, Youdo aot have © Reference variables can always hold reference to subclass instances. In particular, the root class OBJECT can hold references to any object. Using the normal method call or attribute access notation, you can only access components of the class that was used to define the reference variable, Only a dynamic invoke allows the user to access statically unknown methods, For example, if a subclass ship had an additional method sink, you could not call it statically through a reference of type REF TO vessel, but you could call it using the dynamic method call. DATA: vessel TYPE REF TO vessel, ship TYPE REF TO ship. CREATE OBJECT ship EXPORTING name = Titanic’ CALL METHOD ship->ariver 20 ) MOVE ship TO vessel CALL METHOD vessel->drive( 10 ). Listing 4 declares two reference variables, one of type vessel and one of type ship. A class ship object is created, The IMPORT parameter of its constructor is filed, The object can be accessed by both reference variables. In both cases, the method drive that is declared in class vessel is called. But you cannot call the method write with reference variable vessel. ‘The implicit calling of methods that are redefined in subclasses means that, with the superclass's interface, a method call accesses different method implementations in different subclasses. This has an important consequence: A subclass should never change the semantics of a method via redefinition. A subclass must always do more than the superclass but never take anything away, Interfaces. The public components of a class define the external point of contact for the class. They define the semantic interface specific to this class. As an illustration, a Customer class would have a Customerld, and an Order class would have an Orderld as well as lots of specific methods, However, there are many cases when we want another kind of polymorphism, one that is independent of inheritance. Consider the following examples: ‘The ArchiveManager class wants to define what it needs in order to archive a class in a special interface and then access all different classes uniformly through that interface. It doesn't care what specific class it is accessing, It only cares about the archiving aspect. All classes that want to be archived must implement the IF_Archive interface. In the same way, a WorkflowManager class would define an IF_Workfiow interface, and all classes that want to participate in the workflow must implement this interface. ‘The general concept of interfaces is this: An interface is a separate language construct that is allowed to define components (such as in the public section of a class) but without implementation. Classes can implement one or more interfaces in their public section, thereby extending this section. Interfaces can also be used to define reference variables of type REF TO interface. These interface references only show those components that are defined in the interface, regardless of the implementing class. When a class implements an interface, we can get a reference to any implemented interface by way of simple assignment of the form iref = oref. Interfaces in ABAP Objects. Like classes, you can define interfaces globally in the class library or locally within an ABAP program. Interfaces are defined between the INTERFACE and ENDINTERFACE statements. They can contain the same components as classes. An interface’s methods are not implemented in the interface itself, but must be implemented in the classes that implement the interface. You do not have to scsigntte in face comporent pa vsbiity area, Intec allcomponens auiomateall bela tothe pubic ‘he form mucerp.allcomponemsolan mpk ented iertoce cppear wifin ite cass wih the name pret Inte. To aco#se @ Component comp ofan ntsrace within cles orwhen veing a clos relstence. jou must os he rameintheamp. Howsver when using an mince rterence. you car speciy the meiace Components dice, sino the interlace ‘olow nos ony shows the componoric of fat nterace, Whib use the ramesiaiscomp imide te inpementng clos, dw User of he evace ust wile Hot omy Implemented interface components ar ly squvelnlto normal caus components. They exten the outer ‘Sjer pubic cecton) othe lass At uoere can acceesoth tha caesspecte puble componsrtaae wel a2 the components of he inerace ‘One clas can mokmentstveral nelaces,andeach mleiace canbe mplementidby many clases. Wan cbs inplemerisan interlace. immediately hac ts alrbutee and events (ove Leting 5) butit uct shotner meanso! polymorphism in ABAP Objects. As for edetined methods wit nhertance, the impkirentatan of en interlace method sncull confirm the semantics delved he erlace een [aeREA a oe s,s cnet gn ernie [een Ea gion mre cal fo assign the interface components to a visibility area. Instead, all components automatically belong to the Public section of the class implementing the interface, ‘You implement an interface in a class by using the statement INTERFACES in the public section, which causes the components of the interface to be added to the public components of that class, all with ames of the form intf~comp. All components of an implemented interface appear within the class with the name prefix intf~. To access a component comp of an interface within a class or when using a class reference, you must use the name intf~comp. However, when using an interface reference, you can specify the interface components directly, since the interface reference only shows the components of that interface. While we use the names intf~comp inside the implementing class, the users of the interface just write iref->comp. Implemented interface components are fully equivalent to normal class components, They extend the outer layer (public section) of the class. All users can access both the class-specific public components as well as the components of the interface. (One class can implement several interfaces, and each interface can be implemented by many classes. ‘When a class implements an interface, it immediately has its attributes and events (see Listing 5), but it must implement all methods of the implemented interfaces in its implementation part. The interface's methods can be implemented differently in each implementing class. Therefore, in addition to inheritance, interfaces provide another means of polymorphism in ABAP Objects. As for redefined methods with inheritance, the implementation of an interface method should confirm to the semantics defined in the interface. INTERFACE status. METHODS write. ENDINTERFACE CLASS ship DEFINITION INHERITING FROM vessel. PUBLIC SECTION. INTERFACES status... ENDCLASS CLASS ship IMPLEMENTATION. METHOD status~write DATA id. id = me->get_id(). WRITE: / name, ‘is vessel, i, ‘and has speed’, speed, ENDMETHOD. ... ENDCLASS, CLASS coast_guard DEFINITION. PUBLIC SECTION. INTERFACES status. ALIASES write FOR status-write, PRIVATE SECTION DATA caller TYPE string. ENDCLASS. CLASS coast_guard IMPLEMENTATION. METHOD status~wrte, IF caller IS INITIAL WRITE: "Coast guard recelved no call, ELSE. WRITE: "Coast guard received a cal from, caller. ENDIF. ENDMETHOD. ENDCLASS. sting Sdetines an interlace status Leonia one meio wile The clus shi wplces it ows method lite by mpsimentng he imsitece situs Another Cs, coast quorc, b derined Mat ais IMpEmen Beth chsses implement the interface methoe staus~wite "Nested interfaces: By using the INTERFACES otatementwthin the intdace definion, youcan dete tested interfaces hen an interocs contains a nentad eoripanent intros, his ira inerfacs annem Ae tne component Tie conponsnisel tie sentaiedietane am hotavomatoaly able nthe srcleing ‘nertace. To make a component of costined iierace component yb onthe hgh (enclosing) evel You can use he ALIASES samme “interface references: deades teorence verabiee declared wth respecto aces, ASAP Copcts abo provides reference varabies deciored wilh recpectio an nierlace. These ierlacerelerence verables expose ‘ny the components defined inthe nernce seguidiss ofthe molimestng clase Uh tie TYPE REE TO BATA Satan NPE FECT. |e parrncieere = Thee pein Tooke te Listing 8 decaree a arable Sats and an ineinal abe aus lab ao nefoce erence vanes. The ‘conten of voces relerencs Yarns poning objert of shp and coast ques. are appended f that Inisral table By ooning on the neal able, the inrlace method wie © accessed in both abject. Listing 8 nd coast guards do nol have mucitele common, te use can expect he eae semantics fom the ‘nierace methed wie Flue 3 stows te neal abe of nleiace references potting b objets of aifeent closes hat mpbment commen meric om ° Listing 5 defines an interface status. It contains one method, write. The class ship replaces its own method write by implementing the interface status, Another class, coast_guard, is defined that also implements status. Both classes implement the interface method status-wrte. “Nested interfaces: By using the INTERFACES statement within the interface definition, you can define nested interfaces. When an interface contains a nested component interface, this inner interface appears as one component. The components of the contained interface are not automatically visible in the enclosing interface. To make a component of a contained interface component visible on the higher (enclosing) level, you can use the ALIASES statement. “Interface references: Besides reference variables declared with respect to a class, ABAP Objects also provides reference variables declared with respect to an interface. Those interface reference variables expose only the components defined in the interface, regardless of the implementing class. DATA: status TYPE REF TO status, status_tab TYPE TABLE OF REF TO status. DATA ship TYPE REF TO ship. DATA stalion TYPE REF TO coast_guard CREATE OBJECT ship EXPORTING name “Titani¢. APPEND ship TO status, tab. CREATE OBJECT station. APPEND station TO status_tab LOOP AT status tab INTO status. CALL METHOD status->wrte, ENDLOOP. Listing 6 declares a variable status and an intemal table status_tab as interface reference variables. The contents of two class reference variables, pointing to objects of ship and coast_guard, are appended to that internal table. By looping on the internal table, the interface method write is accessed in both objects. Listing 6 shows how objects of two different classes are accessed by reference variables of one kind. Although ships and coast guards do not have much else in common, the user can expect the same semantics from the interface method write. Figure 3 shows the intemal table of interface references pointing to objects of different classes that implement a common interface. i STATUS_TAB J 10 Events. Event generally anrounce that an objots state has changed or tal something hanpe ed thet may ‘bjses, Tey ate espectaly use y 8GUI envigemen; Duta abo good f1 Hose) coupling subeyste ns snd or voatow ‘The nase concept ot metneds i: When ane objec! Acalls @ method of another cbpct S.A muctknow B.A noe! faveae abut that sa eisence 18. Wihevents the situation is dfferent They wok by publish and stbscrbe.One class A defnesan even'e that maybe of intrect bother claseesicbpects When clase B wants fo ect he eventeo! A tines. Sottec orca. The Key ests that handlercan be stacted toda mete wihoutcraaging the ere? code “Events in ABAP Objects: Events are anotherkind of component in cesses. They are declared inthe declntionpartofclaes and mizd n te mstiods. You decive suertsby esing the iammens VENTS for parameters ton ine Wgerng chpcto the hander. Each instance event kas ar xin impli parameter faled SENDER. The SENDER data ype Ia eleence varable loth respesive sender css. State everts canbe bed in ary method ofthe declaring Clas, whereas instance events can ony be raked in nstance matheds. You race an eventina method using te RAISE EVENT satement and you pass Srouments using the EXBORTING cinass Forintnnoe avert the sytem automata passes he ple Signature (names and Npeso! ammeter) 0! peated ut taken tom the eve tio be hanced However, he event harder meveddees #0! have to accept and use alo! the pararelet hat the ever ‘elines An event hades methed can accept tne mpict psrametr SENOEA ike anyother MPORTNG [Smatre PROn yee foassse aer enero speed sat set Ege ever eneomes cl [rime men eve at ‘Fup neon recon ee Events. Events generally announce that an object's state has changed or that something happened that may be of interest to others, They are like outbound method calls and enable a different kind of coupling between objects. They are especially useful in a GUI environment, but are also good for loosely coupling subsystems and for worktiow. The basic concept of methods is: When one object A calls a method of another object B, A must know B. A must have an attribute that is a reference to B With events, the situation is different: They work by publish and subscribe. One class A defines an event e that may be of interest to other classes/objects. When class B wants to react to the event e of A, it defines a handler method h for that event. At run time, an object of B registers its method h as a handler for that event of a sender object of class A. When the abject A now raises event e, all registered handlers for that event are notified or called. The key issue is that a handler can be attached to do more without changing the sender's code, “Events in ABAP Objects: Events are another kind of component in classes. They are declared in the declaration part of a class and raised in its methods. You declare events by using the statements EVENTS for instance events and CLASS-EVENTS for static events. Events can have EXPORTING parameters to pass parameters from the triggering object to the handler. Each instance event has an additional implicit parameter called SENDER, The SENDER data type is a reference variable to the respective sender class. Static events can be raised in any method of the declaring class, whereas instance events can only be raised in instance methods. You raise an event in a method using the RAISE EVENT statement, and you pass arguments using the EXPORTING clause. For instance events, the system automatically passes the implicit parameter SENDER, which is a reference pointing to the object raising the event. ‘Any class may contain event handler methods for events of other classes. The event handler method signature (names and types of parameters) is not repeated but is taken from the event to be handled, However, the event handler method does not have to accept and use all of the parameters that the event defines. An event handler method can accept the implicit parameter SENDER like any other IMPORTING parameter, allowing it to access the triggering instance, The declaration of events and respective event handler methods in classes constitutes the stalic part of publish and subscribe. CLASS ship DEFINITION INHERITING FROM vessel. PUBLIC SECTION. EVENTS emergency_call... ENDCLASS. CLASS ship IMPLEMENTATION. METHOD dive, IF speed > max_speed. . RAISE EVENT emergency_call. ENDIF. ENDMETHOD. ... ENDCLASS. CLASS coast_guard DEFINITION. PUBLIC SECTION, METHODS receive FOR EVENT emergency_call OF ship IMPORTING sender " tea 7 ces an ven omer a is ep He atu peebecomes Mee a ents: Ifyoudeclre an event hander method ina class, tho instances ofthe clos, orthe class ‘lot tandes meinogs i coreenehdug eventtrgge seller immece evens of Salk events. The SET HANDLER statement alse hasan addiion ACTIVATION, which albws you t gist and deregistr handlers name, CALL METHOD write, ENDMETHOD. ... ENDCLASS. Listing 7 declares an event emergency_call in class ship. If the attribute speed becomes higher than max_speed in method drive, the event is raised. A method receive is declared as an event handler in class coast_guard “Handling events: If you declare an event handler method in a class, the instances of the class, or the class itself, are then capable of handling the event. if you want an event handler method to react to an event, you must define at run time the trigger to which you want it to respond with the SET HANDLER statement. It inks a list of handler methods to corresponding event triggers—either instance events or static events. The SET HANDLER statement also has an addition ACTIVATION, which allows you to register and deregister handlers dynamically. Triggering events in methods and registering event handler methods at run time constitutes the dynamic part of publish and subscribe. DATA: ship TYPE REF TO ship, station TYPE REF TO coast_guard. CREATE OBJECT: ship EXPORTING name = Titanic, station. SET HANDLER station >receive FOR ship. DOS TIMES, CALL METHOD ship->drive( 10 ). ENNDO. Listing 8 registers the method receive in an instance of class coast_guard as a handler for the event emergency_call in an instance of class ship, For each SET HANDLER statement, the system creates an entry in an event handler table (see Figure 4), where a handler table belongs to each instance or class that can trigger instance or static events. Itis invisible to the user and contains the names of the handler methods and references to the registered handling instances. When an event is triggered, the system searches the event handler table of the corresponding object or class and executes the listed methods in their instances in the case of instance handler methods, or classes in the case of static handler methods. You can delete single entries from the handler table using the ACTIVATION addition of the SET HANDLER statement. If the triggering instance is deleted by the garbage collector, the entire handler table, including all its references, is deleted. 2 ‘Stores viable dose, Hancler fle sates therfore. aft the Met of copia The msent that our ‘xampl te instance coast quard>f not deleted by the garbage collector es ng as ts regeleed bt Finaly events ns wellastheic ander methods. can bo be defined in nfeiaces Adlon. thm are njecs project You can reach nin aluargen.neymann@ sap-ay Horst Keller i sano ectvica iter nthe SAP ABAP & GUI Group, He documents tne ABAF lenyuage with ‘nanphasis on ABA? Objects He also develops and leeches classes on ASAP propramming. You can f2a2h hi athorstheler@sap-29 de JCOAST_..> STATION SHIP Events| RECEIVE SHIP i ‘A reference to an instance in a handler table counts as a use of the instance, just as a reference in a reference variable does. Handler table entries, therefore, affect the lifetime of objects. This means that in our example, the instance j is not deleted by the garbage collector as long as itis registered for event handling, even if the reference variable station is cleared. Finally, events, as well as their handler methods, can also be defined in interfaces. Additionally, there are some powerful mass registration variants to register a handler for all instances of a class and all classes Implementing a certain interface. Jargen Heymann is senior developer in the SAP ABAP Language Group. He is a key architect in the ABAP Objects project. You can reach him at juergen.heymann@sap-ag.de. Horst Keller is senior technical writer in the SAP ABAP & GUI Group. He documents the ABAP language with an emphasis on ABAP Objects. He also develops and teaches classes on ABAP programming. You can reach him at horst.keller@sap-ag.de. 13

You might also like