Professional Documents
Culture Documents
General What is Object Orientation? From Function Groups to Objects The Basics of ABAP Objects Classes Object Handling eclaring and Calling !ethods "pecial "ections on ABAP Objects #nheritance #nterfaces Triggering and Handling $%ents Class and #nterface Pools
!bjects form a capsule which combines the character to the respective behaviour. !bjects should enable programmers to map a real problem and its proposed software solution on a one-to-one basis. Typical objects in a business environment are, for e"ample, #$ustomer%, #!rder%, or #Invoice%. &rom 'elease (.) onwards, the *usiness !bject 'epository (*!' of +,- .eb ,pplicaton +erver ,*,has contained e"amples of such objects. The *!' object model will be integrated into ,*,- !bjects in the ne"t 'elease by migrating the *!' object types to the ,*,- class library. , comprehensive introduction to object orientation as a whole would go far beyond the limits of this introduction to ,*,- !bjects. This documentation introduces a selection of terms that are used universally in object orientation and also occur in ,*,- !bjects. In subse/uent sections, it goes on to discuss in more detail how these terms are used in ,*,- !bjects. The end of this section contains a list of further reading, with a selection of titles about object orientation.
Objects
Objects are instances of classes& The' contain data and pro%ides ser%ices& The data forms the attributes of the object& The ser%ices are (no)n as methods *also (no)n as operations or functions+& T'picall', methods operate on pri%ate data *the attributes, or state of the object+, )hich is onl' %isible to the methods of the object& Thus the attributes of an object cannot be changed directl' b' the user, but onl' b' the methods of the object& This guarantees the internal consistenc' of the object&
Classes
Classes describe objects& From a technical point of %ie), objects are runtime instances of a class& #n theor', 'ou can create an' number of objects based on a single class& $ach instance *object+ of a class has a uni-ue identit' and its o)n set of %alues for its attributes&
Object References
#n a program, 'ou identif' and address objects using uni-ue object references& Object references allo) 'ou to access the attributes and methods of an object&
In object-oriented programming, objects usually have the following properties:
Encapsulation
Objects restrict the %isibilit' of their resources *attributes and methods+ to other users& $%er' object has an interface, )hich determines ho) other objects can interact )ith it& The implementation of the object is encapsulated, that is, in%isible outside the object itself&
Inheritance
.ou can use an e/isting class to deri%e a ne) class& eri%ed classes inherit the data and methods of the superclass& Ho)e%er, the' can o%er)rite e/isting methods, and also add ne) ones&
Polymorphism
#dentical *identicall'0named+ methods beha%e differentl' in different classes& #n ABAP Objects, pol'morphism is implemented b' redefining methods during inheritance and b' using constructs called interfaces&
Comple/ soft)are s'stems become easier to understand, since object0oriented structuring pro%ides a closer representation of realit' than other programming techni-ues& #n a )ell0designed object0oriented s'stem, it should be possible to implement changes at class le%el, )ithout ha%ing to ma(e alterations at other points in the s'stem& This reduces the o%erall amount of maintenance re-uired& Through pol'morphism and inheritance, object0oriented programming allo)s 'ou to reuse indi%idual components& #n an object0oriented s'stem, the amount of )or( in%ol%ed in re%ising and maintaining the s'stem is reduced, since man' problems can be detected and corrected in the design phase&
,chieving these goals re/uires:
Object0oriented programming techni-ues do not necessaril' depend on object0oriented programming languages& Ho)e%er, the efficienc' of object0oriented programming depends directl' on ho) object0 oriented language techni-ues are implemented in the s'stem (ernel& Object0oriented tools
Object0oriented tools allo) 'ou to create object0oriented programs in object0oriented languages& The' allo) 'ou to model and store de%elopment objects and the relationships bet)een them& Object0oriented modeling
The object0orientation modeling of a soft)are s'stem is the most important, most time0consuming, and most difficult re-uirement for attaining the abo%e goals& Object0oriented design in%ol%es more than just object0oriented programming, and pro%ides logical ad%antages that are independent of the actual implementation&
This section of the ,*,- 0ser%s 1uide provides an overview of the object-oriented e"tension of the ,*,- language. .e have used simple e"amples to demonstrate how to use the new features. 2owever, these are not intended to be a model for object-oriented design. 3ore detailed information about each of the ,*,- !bjects statements is contained in the keyword documentation in the ,*,4ditor. &or a comprehensive introduction to object-oriented software development, you should read one or more of the titles listed below.
Further Reading
There are many books about object orientation, object-oriented programming languages, objectoriented analysis and design, project management for !! projects, patterns and frameworks, and so on. This is a small selection of good books covering the most important topics:
Scott Ambler, The Object Primer, SIGS Books & Multime ia !"##$%, ISB&' "(()()*"+(
A %er' good introduction to object orientation for programmers& #t pro%ides comprehensi%e e/planations of all essential OO concepts, and contains a procedure model for learning OO -uic(l' and thoroughl'& #t is eas' to read and practical, but still theoreticall'0founded& Gra , Booch, Object Solutions' Mana-in- the Object.Oriente Project, A /o !"##0%, ISB&' 1(10210#)+ ison.Wesle, Pub
A good boo( about all of the non0technical aspects of OO that are e-uall' important for effecti%e object0 oriented programming& $as' to read and full of practical tips& Martin 3o4ler, 5M6 7istille ' A88l,in- the Stan ar Object Mo elin- 6an-ua-e, A Wesle, Pub /o !"##+%, ISB&' 1*1"2*0$2* ison.
An e/cellent boo( about 1!2 *1nified !odeling 2anguage 0 the ne) standardi3ed OO language and notation for modeling+& Assumes (no)ledge and e/perience of object orientation& 9rich Gamma, :ichar ;elm, :al8h <ohnson an <ohn =lissi es, 7esi-n Patterns> 9lements of :eusable Object.Oriente Soft4are, A ison.Wesle, Pub /o !"##(%, ISB&' 1*1"$2)#(( Pro%ides a pattern, sho)ing ho) recurring design problems can be sol%ed using objects& This is the first big pattern boo(, containing man' e/amples of good OO design& <ames :umbau-h, OMT Insi-hts' Pers8ecti?es on Mo elin- from the <ournal of Object. Oriente Pro-rammin-, Prentice ;all !"##$%, ISB&' 1"2()$#$0* A collection of articles addressing the man' -uestions and problems of OO anal'sis and design, implementation, dependenc' management, and so on& Highl' recommended&
Notes
If you are new to object-orientation, you should read +cott ,mbler%s #The !bject -rimer% and then ac/uire some practical e"perience of your own. 5ou should definitely use the $'$ techni/ues described by ,mbler and &owler for object-oriented analysis and design. ,fter this, you should learn 036, since this is the universal !! analysis and design notation. &inally, you should read at least one book about patterns. ,t the beginning of a large !! project, the /uestion immediately arises as to the se/uence in which things should be done, which phases should be finished at what time, how to divide up and organi7e the development work, how to minimi7e risks, how to assemble a good team, and so on and so forth. 3any of the best practices of project management have had to be redefined for the objectoriented world, and the opportunities that this has produced are significant. &or further information about how to use !! in project management, see 1rady *rooch%s book #!bject solutions%, or the chapter entitles #,n outline development process% from 3artin &owler%s book. There are, of course, many other good books about object orientation. The above list does not claim either to be complete, or necessarily to recommend the best books available.
Before 697 6elease :&;, the nearest e-ui%alent of objects in ABAP )ere function modules and function groups& "uppose )e ha%e a function group for processing orders& The attributes of an order correspond to the global data of the function group, )hile the indi%idual function modules represent actions that manipulate that data *methods+& This means that the actual order data is encapsulated in the function group, and is ne%er directl' addressed, but instead onl' through the function modules& #n this )a', the function modules can ensure that the data is consistent& When 'ou run an ABAP program, the s'stem starts a ne) internal session& The internal session has a memor' area that contains the ABAP program and its associated data& When 'ou call a function module, an instance of its function group plus its data, is loaded into the memor' area of the internal session& An ABAP program can load se%eral instances b' calling function modules from ifferent function groups&
The instance of a function group in the memor' area of the internal session almost represents an object in the sense of object orientation& "ee also the definition in the section What is Object Orientation?& When 'ou call a function module, the calling program uses the instance of a function group, based on its description in the Function Builder& The program cannot access the data in the function group directl', but onl' through the function module& The function modules and their parameters are the interface bet)een the function group and the user& The main difference bet)een real object orientation and function groups is that although a program can )or( )ith the instances of se?eral function groups at the same time, it cannot )or( )ith se%eral instances of a sin-le function group& "uppose a program )anted to use se%eral independent counters, or process se%eral orders at the same time& #n this case, 'ou )ould ha%e to adapt the function group to include instance administration, for e/ample, b' using numbers to differentiate bet)een the instances& #n practice, this is %er' a)()ard& Conse-uentl', the data is usuall' stored in the calling program, and the function modules are called to )or( )ith it *structured programming+& One problem is, for e/ample, that all users of the function module must use the same data structures as the function group itself& Changing the internal data structure of a function group affects man' users, and it is often difficult to predict the implications& The onl' )a' to a%oid this is to rel' hea%il' on interfaces and a techni-ue that guarantees that the internal structures of instances )ill remain hidden, allo)ing 'ou to change them later )ithout causing an' problems&
This re-uirement is met b' object orientation& ABAP Objects allo)s 'ou to define data and functions in classes instead of function groups& 1sing classes, an ABAP program can )or( )ith an' number of instances *objects+ based on the same template&
#nstead of loading a single instance of a function group into memor' implicitl' )hen a function module is called, the ABAP program can no) generate the instances of classes e/plicitl' using the ne) ABAP statement CREATE OBJECT& The indi%idual instances represent uni-ue objects& .ou address these using object references& The object references allo) the ABAP program to access the interfaces of the instaces& The follo)ing sections contain more information about classes, objects, interfaces, and object references in ABAP Objects&
"uppose )e ha%e a function group called counter< F1=CT#O=0POO2 counter& ATA count T.P$ i& F1=CT#O= set>counter& ? 2ocal #nterface #!PO6T#=G @A21$*"$T>@A21$+ count A set>%alue& $= F1=CT#O=& F1=CT#O= increment>counter& A 8 TO count& $= F1=CT#O=&
F1=CT#O= get>counter& ? 2ocal #nterface< $BPO6T#=G @A21$*G$T>@A21$+ get>%alue A count& $= F1=CT#O=& The function group counter is used as a counter& #t has a global integer field count, and three function modules, set>counter, increment>counter, and get>counter, that )or( )ith the field& T)o of the function modules ha%e input and output parameters& These form the data interface of the function group& From on object0oriented point of %ie), a function gorup has e/clusi%el' pri%ate attributes and public methods& An' ABAP program can then )or( )ith this function group& For e/ample< REPORT demo_function_group_counter. DATA number TYPE i VALUE .
CALL !U"CT#O" $%ET_COU"TER$ E&PORT#"' (et_)*+ue , number. DO - T#.E%. CALL !U"CT#O" $#"CRE.E"T_COU"TER$. E"DDO. CALL !U"CT#O" $'ET_COU"TER$ #.PORT#"' get_)*+ue , number. /R#TE number. After this section of the program has been processed, the program %ariable number )ill ha%e the %alue C& The program itself cannot access the count field in the function group& Operations on this field are full' encapsulated in the function module& The program can onl' communicate )ith the function group b' calling its function modules&
/lasses
$lasses are templates for objects. $onversely, you can say that the type of an object is the same as its class. , class is an abstract description of an object. 5ou could say that it is a set of instructions for building an object. The attributes of objects are defined by the components of the class, which describe the state and behavior of objects.
There is, however, a significant difference in the way that local and global classes are designed. If you are defining a local class that is only used in a single program, it is usually sufficient to define the outwardly visible components so that it fits into that program. 1lobal classes, on the other hand, must be able to be used anywhere. This means that 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 recogni7e the data type of each interface parameter. The following sections describe how to define local classes and interfaces in an ,*,- program. &or information about how to define local classes and interfaces, refer to the $lass *uilder section of the ,*,- .orkbench documentation.
Structure of a Class
The following statements define the structure of a class:
A class contains components $ach component is assigned to a %isibilit' section Classes implement methods
Class Components
The components of a class make up its contents. ,ll components are declared in the declaration part of the class. The components define the attributes of the objects in a class. .hen you define the class, each component is assigned to one of the three isibility sections, which define the e"ternal interface of the class. ,ll of the components of a class are visible within the class. ,ll components are
in the same namespace. This means that all components of the class must have names that are uni/ue within the class. There are two kinds of components in a class - those that e"ist separately for each object in the class, and those that e"ist only once for the whole class, regardless of the number of instances. Instancespecific components are known as instance components. $omponents that are not instance-specific are called static components. In ,*,- !bjects, classes can define the following components. +ince all components that you can declare in classes can also be declared in interfaces, the following descriptions apply e/ually to interfaces.
!ttributes
,ttributes are internal data fields within a class that can have any ,*,- data type. The state of an object is determined by the contents of its attributes. !ne kind of attribute is the reference variable. 'eference variables allow you to create and address objects. 'eference variables can be defined in classes, allowing you to access objects from within a class. Instance !ttributes The contents of instance attributes define the instance-specific state of an object. 5ou declare them using the DATAstatement. Static !ttributes The contents of static attributes define the state of the class that is valid for all instances of the class. +tatic attributes e"ist once for each class. 5ou declare them using the CLASS-DATA statement. They are accessible for the entire runtime of the class. ,ll of the objects in a class can access its static attributes. If you change a static attribute in an object, the change is visible in all other objects in the class. The technical properties of instance attributes belong to the static properties of a class. It is therefore possible to refer in a 6I<4 addition to the visible attributes of a class = through the class component selector or through reference variables, without prior creation of an object.
"ethods
3ethods 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 also have a parameter interface, with which users can supply them with values when calling them, and receive values back from them The private attributes of a class can only be changed by methods in the same class. The definition and parameter interface of a method is similar to that of function modules. 5ou define a method meth in the definition part of a class and implement it in the implementation part using the following processing block: 34T2!: meth. ... 4;:34T2!:.
5ou can declare local data types and objects in methods in the same way as in other ,*,- procedures (subroutines and function modules . 5ou call methods using the CALL METHOD statement. Instance "ethods 5ou declare instance methods using the METHODSstatement. They can access all of the attributes of a class, and can trigger all of the events of the class. Static "ethods 5ou declare static methods using the CLASS-METHODSstatement. They can only access static attributes and trigger static events. Special "ethods ,s well as normal methods, which you call using CALL METHOD, there are two special methods called constructor and class_constructor that are automatically called when you create an object or when you first access the components of a class.
E ents
!bjects or classes can use events to trigger event handler methods in other objects or classes. In a normal method call, one method can be called by any number of users. .hen an event is triggered, any number of event handler methods can be called. The link between the trigger and the handler is not established until runtime. In a normal method call, the calling program determines the methods that it wants to call. These methods must e"ist. .ith events, the handler determines the events to which it wants to react. There does not have to be a handler method registered for every event. The events of a class can be triggered in the methods of the same class using the RAISE EVENT statement. 5ou can declare a method of the same or a different class as an event handler method for the event evt of class class using the addition FOR EVENT evt OF class. 4vents have a similar parameter interface to methods, but only have output parameters. These parameters are passed by the trigger (RAISE EVENTstatement 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. The trigger and handlers can be objects or classes, depending on whether you have instance or static events and event handler methods. .hen an event is triggered, the corresponding event handler methods are e"ecuted in all registered handling classes. Instance E ents 5ou declare instance events using the EVENTSstatement. ,n instance event can only be triggered in an instance method. Static E ents 5ou declare static events using the CLASS-EVENTSstatement. ,ll methods (instance and static methods can trigger static events. +tatic events are the only type of event that can be triggered in a static method. +ee also Triggering and 2andling 4vents.
#ypes
5ou can define your own ,*,- data types within a class using the TYPESstatement. Types are not instance-specific, and e"ist once only for all of the objects in a class.
Constants
$onstants are special static attributes. 5ou set their values when you declare them, and they can then no longer be changed. 5ou declare constants using the CONSTANTS statement. $onstants are not instance-specific, and e"ist once only for all of the objects in a class.
Visibility Sections
5ou can divide the declaration part of a class into up to three visibility areas: $6,++ class :4&I;ITI!;. -0*6I$ +4$TI!;. ... -'!T4$T4: +4$TI!;. ... -'I>,T4 +4$TI!;. ... 4;:$6,++. These areas define the e"ternal visibility of the class components, that is, the interface between the class and its users. 4ach component of a class must be assigned to one of the visibility sections.
Public Section
,ll of the components declared in the public section are accessible to all users of the class, and to the methods of the class and any classes that inherit from it. The public components of the class form the interface bet$een the class and its users.
Protected Section
,ll of the components declared in the protected section are accessible to all methods of the class and of classes that inherit from it. -rotected components form a special interface bet$een a class and its subclasses. +ince inheritance is not active in 'elease 9.?*, the protected section currently has the same effect as the private section.
Encapsulation
The three visibility areas are the basis for one of the important features of object orientation encapsulation. .hen you define a class, you should take great care in designing the public components, and try to declare as few public components as possible. The public components of global classes may not be changed once you have released the class. &or e"ample, public attributes are visible e"ternally, and form a part of the interface between an object and its users. If you want to encapsulate the state of an object fully, you cannot declare any public attributes.
,s well as defining the visibility of an attribute, you can also protect it from changes using the READONLY addition.
The left0hand side of the illustration sho)s the declaration and implementation parts of a local class C0& The right0hand side illustrates the structure of the class )ith the components in their respecti%e %isibilit' areas, and the implementation of the methods& The public components of the class form the interface bet4een the class an its users& The protected components are an interface to the subclasses of C0& The pri%ate components are not %isible e/ternall', and are full' encapsulated in the class& The methods in the implementation part ha%e unrestricted access to all components of the class&
CLA%% counter DE!#"#T#O". PUBL#C %ECT#O". .ET1OD%2 (et #.PORT#"' )*+ue3(et_)*+ue4 TYPE i5 increment5 get E&PORT#"' )*+ue3get_)*+ue4 TYPE i. PR#VATE %ECT#O". DATA count TYPE i. E"DCLA%%. CLA%% counter #.PLE.E"TAT#O". .ET1OD (et. count , (et_)*+ue. E"D.ET1OD. .ET1OD increment. ADD 0 TO count. E"D.ET1OD. .ET1OD get. get_)*+ue , count. E"D.ET1OD. E"DCLA%%. The class counter contains three public methods (et, increment, and get& $ach of these )or(s )ith the pri%ate integer field count& T)o of the methods ha%e input and output parameters& These form the data interface of the class& The field count is not out)ardl' %isible& The e/ample in the section Wor(ing )ith Objects sho)s ho) 'ou can create instances of the class counter&
Object References
To access an object from an ,*,- program, you use only object references. !bject references are pointers to objects. In ,*,-, they are always contained in object reference variables.
Creating Objects
;ow that you defined a class reference variable cre with reference to a class class, you can now create an instance (object of the class. $'4,T4 !*B4$T cref CT5-4 classD. This statement creates an instance of the class class, and the reference variable cre contains a reference to the object. 5ou do not need the TYPE class addition in this case. This addition is only important in the following two situations: ). if you use inheritance and want to create an instance of a class class with a class reference variable cre which does not have the type of the class class, or 8. if you use interfaces and want to create an instance of a class classwith an interface reference variable #re . ,fter TYPE you can specify the class dynamically as the contents of a field using the standard parenthesis synta".
To access an attribute *ttr< ref0Dattr To call a method met6< CA22 !$THO ref0Dmeth
5ou can access static components using the class name or the class component selector EA as well as the reference variable. It is also possible to address the static components of a class before an object has been created.
To access a static attribute *ttr< c+*((ADattr To call a static method met6< CA22 !$THO classADmeth
;ote that the properties of instance attributes behave like static components. It is therefore possible to refer in a 6I<4 addition to the visible attributes of a class = through the class component selector or through reference variables, without prior creation of an object. 4ach class implicitly contains the reference variable !e. In objects, the reference variable !ealways contains a reference to the respective object itself and is therefore also referred to as the selfreference. .ithin a class, you can use the self-reference !e to access the individual class components:
To access an attribute *ttr of 'our class< me0Dattr To call a method met6 of 'our class< CA22 !$THO me0Dmeth
.hen you work with attributes of your own class in methods, you do not need to specify a reference variable. The self-reference !e is implicitly set by the system. +elf-references allow an object to give other objects a reference to it. 5ou can also access attributes in methods from within an object even if they are obscured by local attributes of the method.
cref) E cref8 the two class references cre & and cre ' must have the same type, that is, they must either refer to the same class, or the class of cre & must be a superclass of the class of cre '. In particular, cre & can be the predefined empty class O$%ECT. The class O$%ECT is the superclass of all classes in ,*,!bjects and does not have any components. It has the same function for reference variables as the data type ANY has for normal variables. 'eference variables with the type O$%ECT can function as containers for passing references. 2owever, you cannot use them to address objects. In addition, the following relations with interface reference variables can be checked statically. iref) E iref8. *oth interface references must refer to the same interface, or the interface of #re ' must be nested, containing the interface of #re & as a component. iref) E cref). The class of the class reference cre & or one of its superclasses must implement the interface of the interface reference #re &. The interface can be implemented either directly or by using a nested interface containing the interface of #re & as a component. cref) E iref). In this case, the class of cre & must be the class O$%ECT, that is, the reference variable cre & must have the type REF TO O$%ECT.
Casting
.henever a static type check is not possible or when the type checks are to be performed at program runtime, you must use the statement 3!>4 ... FT! ... or the casting operator (() . The casting assignment replaces the assignment operator () . In the MOVE*** ( TO statement, or when you use the casting assignment, there is no static type check. Instead, the system checks at runtime whether the object reference in the source variable points to an object to which the object reference in the target variable can also point. If the assignment is possible, the system makes it, otherwise, the catchable runtime error 3!>4G$,+TG4''!' occurs. +ynta" rules force you to use casting whenever a static type check is not possible, for e"ample: cref) FE iref). 2ere, an interface reference is assigned to a class reference. &or the casting to be successful, the object to which #re rpoints must be an object of the same class as the class of the class variable cre & or one of its subclasses..
Object Lifetime
,n object e"ists for as long as it is being used in the program. ,n 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.
,s soon as there are no more references to an object, and so long as none of its methods are registered as event handlers, it is deleted by the automatic memory management (garbage collection . The I: of the object then becomes free, and can be used by a new object.
The above illustration shows a class C& on the left, with its instances represented in the internal session of an ,*,- program on the right. To distinguish them from classes, instances are drawn with rounded corners. The instance names above use the same notation as is used for reference variables in the :ebugger.
The follo)ing e/ample sho)s ho) to create and handle objects of the class counter from the e/ample in the section Classes&
Example
The DATA statement creates a class reference variable CREF1 with type C_COUNTER. This variable can c ntain references t all instances f the class C_COUNTER. The class C_COUNTER m!st be "n wn t the pr #ram when the DATA statement cc!rs. $ ! can either %eclare it l cally bef re the %ata statement in the same pr #ram& r #l bally !sin# the Class '!il%er. The c ntents f CREF1 are initial. The reference % es n t p int t an instance.
Example
The CREATE O'(ECT statement creates an b)ect *instance+ f the class C_COUNTER. The reference in the reference variable CREF_1 p ints t this b)ect. This instance f the class C_COUNTER is calle% C_COUNTER,1-& beca!se this is h w the c ntents f the b)ect variable REF_COUNTER_1 are %isplaye% in the %eb!##er after the CREATE O'(ECT statement has been e.ec!te%. This name is nly !se% f r internal pr #ram a%ministrati n / it % es n t cc!r in the A'A0 pr #ram itself.
Example
The A'A0 pr #ram can access the p!blic c mp nents f the b)ect !sin# the reference variable CREF1& that is in this case& it can call the p!blic meth %s f the class C_COUNTER. After the pr #ram n the left/han% si%e has been e.ec!te%& the pr #ram variables NU1'ER an% the private b)ect attrib!te COUNT b th have the val!e 2.
Example
This %eclares three %ifferent class reference variables f r the class C_COUNTER. All f the references are initial.
Example
The system creates three b)ects f the class fr m the three class reference variables. The references in the three reference variables each p int t ne f these b)ects. 3n the internal pr #ram mana#ement& the in%ivi%!al instances are calle% C_COUNTER,1-& C_COUNTER,4-& an% C_COUNTER,5-. They are name% in the r%er in which they were create%.
Example
The A'A0 pr #ram can !se the reference variables t access in%ivi%!al b)ects& that is in this case& t call the p!blic meth %s f the class C_COUNTER. Each b)ect has its wn state& since the private instance attrib!te COUNT has a separate val!e f r each b)ect. The pr #ram n the left/han% si%e a%ministers several in%epen%ent c !nters.
Example
6ere& three class reference variables are %eclare% f r the class C_COUNTER& an% tw b)ects are create% f r the class. The references in the reference variables CREF1 an% CREF4 each p int t ne f these b)ects. The reference in CREF5 is initial.
Example
After the 1O7E statement& CREF5 c ntains the same reference as CREF4& an% b th references p int t the b)ect C_COUNTER,4-. A !ser can th!s !se either reference t a%%ress the b)ect C_COUNTER,4-.
Example
The C8EAR statement resets the reference in CREF4 t its initial val!e. The reference variable CREF4 then c ntains the same val!e as it %i% imme%iately after its %eclarati n& an% % es n t p int t an b)ect any m re.
Example
The effect f the assi#nment statement is t c py the reference fr m CREF1 t CREF4. As a res!lt& the reference in CREF5 als p ints t the b)ect C_COUNTER,1-. N m re references p int t the b)ect C_COUNTER,4-& an% it is a!t matically %elete% by the #arba#e c llecti n. The internal name C_COUNTER,4- is n w free a#ain.
(eclaring "ethods
5ou can declare methods in the declaration part of a class or in an interface. To declare instance methods, use the following statement: 34T2!:+ meth I3-!'TI;1 C>,604(D#) i8 ... C D T5-4 type C!-TI!;,6D... 4H-!'TI;1 C>,604(De) e8 ... C D T5-4 type ... $2,;1I;1 C>,604(Dc) c8 ... C D T5-4 type C!-TI!;,6D... '4T0';I;1 >,604(r 4H$4-TI!;+ e+c) e"c8 ... . and the appropriate additions. To declare static methods, use the following statement: $6,++-34T2!:+ meth... *oth statements have the same synta".
.hen you declare a method, you also define its parameter interface using the additions IMPORTIN,, E-PORTIN,, CHAN,IN,, and RET.RNIN,. The additions define the input, output, and inputIoutput parameters, and the return code. They also define the attributes of the interface parameters, namely whether a parameter is to be passed by reference or value (VAL.E , its type (TYPE , and whether it is optional (OPTIONAL, DEFA.LT . 0nlike in function modules, the default way of passing a parameter in a method is by reference. To pass a parameter by value, you must do so e"plicitly using the VAL.E addition. The return value (RET.RNIN, parameter must always be passed e"plicitly as a value. This is suitable for methods that return a single output value. If you use it, you cannot use E-PORTIN, or CHAN,IN, parameters. ,s in function modules, you can use e"ception parameters (E-CEPTIONS to allow the user to react to error situations when the method is e"ecuted.
Implementing "ethods
5ou must implement all of the methods in a class in the implementation part of the class in a 34T2!: meth. ... 4;:34T2!:. block. .hen you implement the method, you do not have to specify any interface parameters, since these are defined in the method declaration. The interface parameters of a method behave like local variables within the method implementation. 5ou can define additional local variables within a method using the DATA statement. ,s in function modules, you can use the RAISE e+ce"t#on and MESSA,E RAISIN, statements to handle error situations. .hen you implement a static method, remember that it can only work with the static attributes of your class. Instance methods can work with both static and instance attributes.
where re is a reference variable whose value points to an instance of the class. >isible instance methods can be called from outside the class using $,66 34T2!: EAmeth... where class is the name of the relevant class. .hen you call a method, you must pass all non-optional input parameters using the E-PORTIN, or CHAN,IN, addition in the CALL METHOD statement. 5ou can (but do not have to import the output parameters into your program using the IMPORTIN, or RECEIVIN, addition. 4/ually, you can (but do not have to handle any e"ceptions triggered by the e"ceptions using the E-CEPTIONS addition. 2owever, this is recommended. 5ou pass and receive values to and from methods in the same way as with function modules, that is, with the synta": ... &ormal parameter E ,ctual parameter after the corresponding addition. The interface parameters (formal parameters are always on the lefthand side of the e/uals sign. The actual parameters are always on the right. The e/uals sign is not an assignment operator in this conte"tJ it merely serves to assign program variables to the interface parameters of the method. If the interface of a method consists only of a single IMPORTIN, parameter, you can use the following shortened form of the method call: $,66 34T2!: method( f . The actual parameter is passed to the input parameters of the method.
If the interface of a method consists only of IMPORTIN, parameters, you can use the following shortened form of the method call: $,66 34T2!: method( i) E f) i8 E f8 ... . 4ach actual parameter
)
CA22 !$THO classAD*f+ CA22 !$THO *c+ADmeth CA22 !$THO *c+AD*f+ Calling a user0defined method met6<
=A!$ for the name of the formal parameter E#= for the t'pe of parameter passing @A21$ of the t'pe RE! TO DATA for the %alue of the actual parameter
The ;,34 column is the uni/ue table key. &or each non-optional parameter you must fill e"actly one line of the internal table. &or each optional parameter you can do this, but are not forced to. The type of parameter passing is determined in the declaration of the method called for each formal parameter. The contents of the <I;: column may therefore be initial. If you want to check the type of parameter passing at runtime, you can assign one of the following constants from the global class $6G,*,-G!*B4$T:4+$' to the <I;: column:
C2>ABAP>OBF$CT $"C6AD$BPO6T#=G for E&PORT#"' parameters C2>ABAP>OBF$CT $"C6AD#!PO6T#=G for #.PORT#"' parameters C2>ABAP>OBF$CT $"C6ADCHA=G#=G for C1A"'#"' parameters C2>ABAP>OBF$CT $"C6AD6$C$#@#=G for RECE#V#"' parameters
The descriptions depend on the view of the caller. If the specified and actual parameter types differ, the system generates the catchable runtime error :5;G$,66G34T2G-,',3G<I;:. 5ou can also use the entries in the <I;: column as an additional key, for e"ample, to read all imported values after the method call. &or the value of the actual parameter, the >,604 reference of the table line must point to a data object containing the re/uested value. 5ou can use the command 14T '4&4'4;$4 in this case. The e"ception table eta1 must be a hash table of the table type ,*,-G4H$-*I;:GT,* or of the line type ,*,-G4H$-*I;:. These types are defined in the ,*,- :ictionary. The table has the following two columns:
=A!$ for the name of the e/ception @A21$ of t'pe i for the %alue to be assigned to (78(ubrc
The ;,34 column is the uni/ue table key. &or each e"ception, you can fill e"actly one line of the internal table. The >,604 component is assigned the numeric value to appear in s2-su1rc after the e"ception is triggered.
)unctional "ethods
&unctional methods are methods with any number of IMPORTIN, parameters and one RET.RNIN, parameter. In addition to CALL METHOD you can also use the following e"pressions at operand positions to call functional methods:
IMPORTING parameters
;one !ne n This notation is currently supported:
$/pression
meth( meth( f oder meth( p E f meth( p) E f) ... pn E fn
for the source field of the .OVE statement in arithmetic e/pressions of the CO.PUTE statement in logical e/pressions in the CA%E statement of the CA%E control structure in the /1E" statement of the CA%E control structure in the /1ERE condition of the statements LOOP AT, DELETE and .OD#!Yfor internal tables
The functional method is entered instead of an operand. .hen the statement is e"ecuted, the method is called and the RET.RNIN, parameter passed back is used as the operand.
The interface ma' onl' consist of #.PORT#"' parameters& $ach #.PORT#"' parameter must be an E&PORT#"' parameter of the e%ent e)t&
The attributes of the parameters are defined in the declaration of the e%ent e)t *EVE"T% statement+ and are adopted b' the e%ent handler method&
+ee also Triggering and 2andling 4vents
Constructors
$onstructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the initial state of a new object or class. There are two types of constructors - instance constructors and static constructors. $onstructors are methods with a predefined name. To use them, you must declare them e"plicitly in the class. The instance constructor of a class is the predefined instance method CONSTR.CTOR. 5ou declare it in the public section as follows: 34T2!:+ $!;+T'0$T!' I3-!'TI;1 C>,604(D#) i8 ...C D T5-4 type C!-TI!;,6D... 4H$4-TI!;+ e+c) e"c8 ... . and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE O$%ECT statement. 5ou can pass the input parameters of the instance constructor and handle its e"ceptions using the E-PORTIN, and E-CEPTIONS additions in the CREATE O$%ECT statement. The static constructor of a class is the predefined static method CLASS_CONSTR.CTOR. 5ou declare it in the public section as follows: $6,++-34T2!:+ $6,++G$!;+T'0$T!'. and implement it in the implementation section like any other method. 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. The methods e"ample shows how to use instance and static constructors.
Overview
This e.ample !ses three classes calle% C_TEA1& C_'39ER& an% C_'3C$C8E. A !ser *a pr #ram+ can create b)ects f the class C_TEA1. On a selecti n screen& the class C_TEA1 as"s f r the n!mber f members f each team. Each b)ect in the class C_TEA1 can create as many instances f the class C_'39ER as there are members in the team. Each instance f the class C_'39ER creates an instances f the class C_'3C$C8E. Each instance f the class C_TEA1 can c mm!nicate with the pr #ram !ser thr !#h an interactive list. The pr #ram !ser can ch se in%ivi%!al team members f r acti ns. The instances f the class C_'39ER all w the pr #ram !ser t ch se the acti n n a f!rther selecti n screen.
Constraints
The A'A0 statements !se% f r list pr cessin# are n t yet f!lly available in A'A0 Ob)ects. 6 wever& t pr %!ce a simple test !tp!t& y ! can !se the f ll win# statements: o o o o ;R3TE <AT= >, ffset-*,len#th-+ ,fU83NE ?930 NE;/83NE
N te: The behavi r f f rmattin# an% interactive list f!ncti ns in their c!rrent state are n t #!arantee%. 3nc mpatible chan#es c !l% cc!r in a f!t!re release.
Declarations
This e.ample is implemente% !sin# local classes& since selecti n screens bel n# t an A'A0 pr #ram& an% cann t be %efine% r calle% in #l bal classes. 'el w are the %efiniti ns f the tw selecti n screens an% three classes: 9999999999999999999999999999999999999999999999999999999999999999999 9 '+ob*+ %e+ection %creen( 9999999999999999999999999999999999999999999999999999999999999999999 %ELECT#O"8%CREE" BE'#" O!2 %CREE" 0:: T#TLE T#T05 L#"E. PARA.ETER% .E.BER% TYPE # DE!AULT 0:. %ELECT#O"8%CREE" E"D O!2 L#"E5 %CREE" 0::. 9888888888888888888888888888888888888888888888888888888888888888888 %ELECT#O"8%CREE" BE'#" O! %CREE" ;:: T#TLE T#T;. PARA.ETER%2 DR#VE RAD#OBUTTO" 'ROUP ACT"5 %TOP RAD#OBUTTO" 'ROUP ACT"5 'EARUP RAD#OBUTTO" 'ROUP ACT"5 'EARDO/" RAD#OBUTTO" 'ROUP ACT". %ELECT#O"8%CREE" E"D O! %CREE" ;::. 9999999999999999999999999999999999999999999999999999999999999999999 9 C+*(( Definition( 9999999999999999999999999999999999999999999999999999999999999999999 CLA%%2 C_B#<ER DE!#"#T#O" DE!ERRED5 C_B#CYCLE DE!#"#T#O" DE!ERRED. 9888888888888888888888888888888888888888888888888888888888888888888 CLA%% C_TEA. DE!#"#T#O". PUBL#C %ECT#O". TYPE%2 B#<ER_RE! TYPE RE! TO C_B#<ER5 B#<ER_RE!_TAB TYPE %TA"DARD TABLE O! B#<ER_RE! /#T1 DE!AULT <EY5 BE'#" O! %TATU%_L#"E_TYPE5 !LA'304 TYPE C5
TE&T03 4 TYPE C5 #D TYPE #5 TE&T;3=4 TYPE C5 TE&T-3>4 TYPE C5 'EAR TYPE #5 TE&T?3=4 TYPE C5 %PEED TYPE #5 E"D O! %TATU%_L#"E_TYPE. CLA%%8.ET1OD%2 CLA%%_CO"%TRUCTOR. .ET1OD%2 CO"%TRUCTOR5 CREATE_TEA.5 %ELECT#O"5 E&ECUT#O". PR#VATE %ECT#O". CLA%%8DATA2 TEA._.E.BER% TYPE #5 COU"TER TYPE #. DATA2 #D TYPE #5 %TATU%_L#"E TYPE %TATU%_L#"E_TYPE5 %TATU%_L#%T TYPE %ORTED TABLE O! %TATU%_L#"E_TYPE /#T1 U"#@UE <EY #D5 B#<ER_TAB TYPE B#<ER_RE!_TAB5 B#<ER_%ELECT#O" L#<E B#<ER_TAB5 B#<ER L#<E L#"E O! B#<ER_TAB. .ET1OD%2 /R#TE_L#%T. E"DCLA%%. 9888888888888888888888888888888888888888888888888888888888888888888 CLA%% C_B#<ER DE!#"#T#O". PUBL#C %ECT#O". .ET1OD%2 CO"%TRUCTOR #.PORT#"' TEA._#D TYPE # .E.BER% TYPE #5 %ELECT_ACT#O"5 %TATU%_L#"E E&PORT#"' L#"E TYPE C_TEA.,A%TATU%_L#"E_TYPE. PR#VATE %ECT#O". CLA%%8DATA COU"TER TYPE #. DATA2 #D TYPE #5 B#<E TYPE RE! TO C_B#CYCLE5 'EAR_%TATU% TYPE # VALUE 05 %PEED_%TATU% TYPE # VALUE :. .ET1OD% B#<ER_ACT#O" #.PORT#"' ACT#O" TYPE #. E"DCLA%%. 9888888888888888888888888888888888888888888888888888888888888888888
CLA%% C_B#CYCLE DE!#"#T#O". PUBL#C %ECT#O". .ET1OD%2 DR#VE E&PORT#"' VELOC#TY TYPE #5 %TOP E&PORT#"' VELOC#TY TYPE #5 C1A"'E_'EAR #.PORT#"' C1A"'E TYPE # RETUR"#"' VALUE3'EAR4 TYPE # E&CEPT#O"% 'EAR_.#" 'EAR_.A&. PR#VATE %ECT#O". DATA2 %PEED TYPE #5 'EAR TYPE # VALUE 0. CO"%TA"T%2 .A&_'EAR TYPE # VALUE 0B5 .#"_'EAR TYPE # VALUE 0. E"DCLA%%. 9999999999999999999999999999999999999999999999999999999999999999999 N te that n ne f the three classes has any p!blic attrib!tes. The states f the classes can nly be chan#e% by their meth %s. The class C_TEA1 c ntains a static c nstr!ct r C8A??_CON?TRUCTOR. C_TEA1 an% C_'39ER b th c ntain instance c nstr!ct rs.
Implementations
The implementati n parts f the classes c ntain the implementati ns f all f the meth %s %eclare% in the c rresp n%in# %eclarati n parts. The interfaces f the meth %s have alrea%y been %efine% in the %eclarati ns. 3n the implementati ns& the interface parameters behave li"e l cal %ata.
-.
The static c nstr!ct r is e.ec!te% bef re the class C_TEA1 is !se% f r the first time in a pr #ram. 3t calls the selecti n screen 1@@ an% sets the static attrib!te TEA1_1E1'ER? t the val!e entere% by the pr #ram !ser. This attrib!te has the same val!e f r all instances f the class C_TEA1.
CO$#!%&C!O% .ET1OD CO"%TRUCTOR. COU"TER , COU"TER D 0. #D , COU"TER. E"D.ET1OD. The instance c nstr!ct r is e.ec!te% %irectly after each instance f the class C_TEA1 is create%. 3t is !se% t c !nt the n!mber f instance f C_TEA1 in the static attrib!te COUNTER& an% assi#ns the c rresp n%in# n!mber t the instance attrib!te 3D f each instance f the class. C%EA!E !EAM .ET1OD CREATE_TEA.. DO TEA._.E.BER% T#.E%. CREATE OBJECT B#<ER E&PORT#"' TEA._#D , #D .E.BER% , TEA._.E.BER%. APPE"D B#<ER TO B#<ER_TAB. CALL .ET1OD B#<ER8A%TATU%_L#"E #.PORT#"' L#"E , %TATU%_L#"E. APPE"D %TATU%_L#"E TO %TATU%_L#%T. E"DDO. E"D.ET1OD. The p!blic instance meth % CREATE_TEA1 can be calle% by any !ser f the class c ntainin# a reference variable with a reference t an instance f the class. 3t is !se% t create instances f the class C_'39ER& !sin# the private reference variable '39ER in the class C_TEA1. $ ! m!st pass b th inp!t parameters f r the instance c nstr!ct r f class C_'39ER in the CREATE O'(ECT statement. The references t the newly/create% instances are inserte% int the private internal table '39ER_TA'. After the meth % has been e.ec!te%& each line f the internal table c ntains a reference t an instance f the class C_'39ER. These references are nly visible within the class C_TEA1. E.ternal !sers cann t a%%ress the b)ects f class C_'39ER. CREATE_TEA1 als calls the meth % ?TATU?_83NE f r each newly/create% b)ect& an% !ses the w r" area ?TATU?_83NE t appen% its !tp!t parameter 83NE t the private internal table ?TATU?_83?T. #E"EC!IO$ .ET1OD %ELECT#O". CLEAR B#<ER_%ELECT#O". DO. READ L#"E %Y8#"DE&. #! %Y8%UBRC EA :. E&#T. E"D#!. #! %Y8L#%ELD:304 , $&$. READ TABLE B#<ER_TAB #"TO B#<ER #"DE& %Y8#"DE&. APPE"D B#<ER TO B#<ER_%ELECT#O". E"D#!. E"DDO. CALL .ET1OD /R#TE_L#%T. E"D.ET1OD. The p!blic instance meth % ?E8ECT3ON can be calle% by any !ser f the class c ntainin# a reference variable with a reference t an instance f the class. 3t selects all f the lines in the c!rrent list in which the chec"b . in the first c l!mn is selecte%. F r these lines& the system c pies the c rresp n%in# reference variables fr m the table '39ER_TA' int an a%%iti nal private internal table '39ER_?E8ECT3ON. ?E8ECT3ON then calls the private meth % ;R3TE_83?T& which %isplays the list. E'EC&!IO$ .ET1OD E&ECUT#O". C1EC< "OT B#<ER_%ELECT#O" #% #"#T#AL. LOOP AT B#<ER_%ELECT#O" #"TO B#<ER. CALL .ET1OD B#<ER8A%ELECT_ACT#O".
CALL .ET1OD B#<ER8A%TATU%_L#"E #.PORT#"' L#"E , %TATU%_L#"E. .OD#!Y TABLE %TATU%_L#%T !RO. %TATU%_L#"E. E"DLOOP. CALL .ET1OD /R#TE_L#%T. E"D.ET1OD. The p!blic instance meth % EAECUT3ON can be calle% by any !ser f the class c ntainin# a reference variable with a reference t an instance f the class. The meth % calls the tw meth %s ?E8ECT_ACT3ON an% ?TATU?_83NE f r each instance f the class C_'39ER f r which there is a reference in the table '39ER_?E8ECT3ON. The line f the table ?TATU?_83?T with the same "ey as the c mp nent 3D in the w r" area ?TATU?_83NE is verwritten an% %isplaye% by the private meth % ;R3TE_83?T. (%I!E "I#! .ET1OD /R#TE_L#%T. %ET T#TLEBAR $T#T$. %Y8L%#"D , :. %<#P TO L#"E 0. PO%#T#O" 0. LOOP AT %TATU%_L#%T #"TO %TATU%_L#"E. /R#TE2 F %TATU%_L#"E8!LA' A% C1EC<BO&5 %TATU%_L#"E8TE&T05 %TATU%_L#"E8#D5 %TATU%_L#"E8TE&T;5 %TATU%_L#"E8TE&T-5 %TATU%_L#"E8'EAR5 %TATU%_L#"E8TE&T?5 %TATU%_L#"E8%PEED. E"DLOOP. E"D.ET1OD. The private instance meth % ;R3TE_83?T can nly be calle% fr m the meth %s f the class C_TEA1. 3t is !se% t %isplay the private internal table ?TATU?_83?T n the basic list *?$/8?3ND B @+ f the pr #ram.
#E"EC! AC!IO$ .ET1OD %ELECT_ACT#O". DATA ACT#V#TY TYPE #. T#T; , $%e+ect *ction for B#<E$. T#T;D;?3-4 , #D. CALL %ELECT#O"8%CREE" ;:: %TART#"' AT C1EC< "OT %Y8%UBRC 'T :. #! 'EARUP , $&$ OR 'EARDO/" , $&$. #! 'EARUP , $&$. ACT#V#TY , 0. EL%E#! 'EARDO/" , $&$. ACT#V#TY , 80. E"D#!. EL%E#! DR#VE , $&$. ACT#V#TY , ;. EL%E#! %TOP , $&$. ACT#V#TY , -. E"D#!. CALL .ET1OD B#<ER_ACT#O"3 ACT#V#TY4. E"D.ET1OD.
0 .
The p!blic instance meth % ?E8ECT_ACT3ON can be calle% by any !ser f the class c ntainin# a reference variable with a reference t an instance f the class. The meth % calls the selecti n screen 4@@ an% analyCes the !ser inp!t. After this& it calls the private meth % '39ER_ACT3ON f the same class. The meth % call !ses the sh rtene% f rm t pass the act!al parameter ACT373T$ t the f rmal parameter ACT3ON. BI)E% AC!IO$ .ET1OD B#<ER_ACT#O". CA%E ACT#O". /1E" 80 OR 0. CALL .ET1OD B#<E8AC1A"'E_'EAR E&PORT#"' C1A"'E , ACT#O" RECE#V#"' 'EAR , 'EAR_%TATU% E&CEPT#O"% 'EAR_.A& , 0 'EAR_.#" , ;. CA%E %Y8%UBRC. /1E" 0. .E%%A'E #-0 3AT4 /#T1 $B#<E$ #D $ i( *+re*d7 *t m*Gim*+ ge*rH$. /1E" ;. .E%%A'E #-0 3AT4 /#T1 $B#<E$ #D $ i( *+re*d7 *t minim*+ ge*rH$. E"DCA%E. /1E" ;. CALL .ET1OD B#<E8ADR#VE #.PORT#"' VELOC#TY , %PEED_%TATU%. /1E" -. CALL .ET1OD B#<E8A%TOP #.PORT#"' VELOC#TY , %PEED_%TATU%. E"DCA%E. E"D.ET1OD. The private instance meth % '39ER_ACT3ON can nly be calle% fr m the meth %s f the class C_'39ER. The meth % calls ther meth %s in the instance f the class C_'3C$C8E t which the reference in the reference variable '39E is p intin#& %epen%in# n the val!e in the inp!t parameter ACT3ON. #!A!&# "I$E .ET1OD %TATU%_L#"E. L#"E8!LA' , %PACE. L#"E8TE&T0 , $BiIer$. L#"E8#D , #D.
, , , , ,
The p!blic instance meth % ?TATU?_83NE can be calle% by any !ser f the class c ntainin# a reference variable with a reference t an instance f the class. 3t fills the str!ct!re% !tp!t parameter 83NE with the c!rrent attrib!te val!es f the c rresp n%in# instance.
f rmal parameter with the same name bsc!res the attrib!te in the meth %& the attrib!te has t be a%%resse% !sin# the self/reference 1E/-DEAR.
9999999999999999999999999999999999999999999999999999999999999999999 9 Progr*m e)ent( 9999999999999999999999999999999999999999999999999999999999999999999 %TART8O!8%ELECT#O". CREATE OBJECT2 TEA._BLUE5 TEA._'REE"5 TEA._RED. CALL .ET1OD2 TEA._BLUE8ACREATE_TEA.5 TEA._'REE"8ACREATE_TEA.5 TEA._RED8ACREATE_TEA.. %ET P!8%TATU% $TEA.L#%T$. /R#TE $ %e+ect * te*mH $ COLOR , ;.
9888888888888888888888888888888888888888888888888888888888888888888 AT U%ER8CO..A"D. CA%E %Y8UCO... /1E" $TEA._BLUE$. COLOR , $BLUE $. !OR.AT COLOR , 0 #"TE"%#!#ED O" #"VER%E O". CALL .ET1OD TEA._BLUE8A%ELECT#O". /1E" $TEA._'REE"$. COLOR , $'REE"$. !OR.AT COLOR , #"TE"%#!#ED O" #"VER%E O". CALL .ET1OD TEA._'REE"8A%ELECT#O".
/1E" $TEA._RED$. COLOR , $RED $. !OR.AT COLOR , > #"TE"%#!#ED O" #"VER%E O". CALL .ET1OD TEA._RED8A%ELECT#O". /1E" $E&ECUT#O"$. CA%E COLOR. /1E" $BLUE $. !OR.AT COLOR , 0 #"TE"%#!#ED O" #"VER%E O". CALL .ET1OD TEA._BLUE8A%ELECT#O". CALL .ET1OD TEA._BLUE8AE&ECUT#O". /1E" $'REE"$. !OR.AT COLOR , #"TE"%#!#ED O" #"VER%E O". CALL .ET1OD TEA._'REE"8A%ELECT#O". CALL .ET1OD TEA._'REE"8AE&ECUT#O". /1E" $RED $. !OR.AT COLOR , > #"TE"%#!#ED O" #"VER%E O". CALL .ET1OD TEA._RED8A%ELECT#O". CALL .ET1OD TEA._RED8AE&ECUT#O". E"DCA%E. E"DCA%E. 9999999999999999999999999999999999999999999999999999999999999999999 The pr #ram c ntains three class reference variables that refer t the class C_TEA1. 3t creates three b)ects fr m the class& t which the references in the reference variables then p int. 3n each b)ect& it calls the meth % CREATE_TEA1. The meth % C8A??_CON?TRUCTOR f class C_TEA1 is e.ec!te% bef re the first f the b)ects is create%. The stat!s TEA183?T f r the basic list all ws the !ser t ch se ne f f !r f!ncti ns:
;hen the !ser ch ses a f!ncti n& the event AT U?ER/CO11AND is tri##ere% an% p!blic meth %s are calle% in ne f the three instances f C_TEA1& %epen%in# n the !serEs ch ice. The !ser can chan#e the state f an b)ect by selectin# the c rresp n%in# line in the stat!s list.
Inheritance
Inheritance allows you to derive a new class from an e"isting class. 5ou do this using the INHERITIN, FROM addition in the $6,++ subclass :4&I;ITI!; I;24'ITI;1 &'!3 superclass. statement. The new class su1class inherits all of the components of the e"isting class su"erclass. The new class is called the subclass of the class from which it is derived. The original class is called the superclass of the new class. If you do not add any new declarations to the subclass, it contains the same components as the superclass. 2owever, only the public and protected components of the superclass are visible in the subclass. ,lthough the private components of the superclass e"ist in the subclass, they are not visible. 5ou can declare private components in a subclass that have the same names as private components of the superclass. 4ach class works with its own private components. 3ethods that a subclass inherits from a superclass use the private attributes of the superclass, and not any private components of the subclass with the same names. If the superclass does not have a private visibility section, the subclass is an e"act replica of the superclass. 2owever, you can add new components to the subclass. This allows you to turn the
subclass into a speciali7ed version of the superclass. If a subclass is itself the superclass of further classes, you introduce a new level of speciali7ation. , class can have more than one direct subclass, but it may only have one direct superclass. This is called single inheritance. .hen subclasses inherit from superclasses and the superclass is itself the subclass of another class, all of the classes involved form an inheritance tree, whose degree of speciali7ation increases with each new hierarchical level you add. $onversely, the classes become more generali7ed until you reach the root node of the inheritance tree. The root node of all inheritance trees in ,*,- !bjects is the predefined empty class O$%ECT. This is the most generali7ed class possible, since it contains neither attributes nor methods. .hen you define a new class, you do not have to specify it e"plicitly as the superclass - the relationship is always implicitly defined. .ithin an inheritance tree, two adjacent nodes are the direct superclass or direct subclass of one another. !ther related nodes are referred to as superclasses and subclasses. The component declarations in a subclass are distributed across all levels of the inheritance tree.
Redefining "ethods
,ll subclasses contain the components of all classes between themselves and the root node in an inheritance tree. The visibility of a component cannot be changed. 2owever, you can use the REDEFINITION addition in the METHODSstatement to redefine an inherited public or protected instance method in a subclass and make its function more speciali7ed. .hen you redefine a method, you cannot change its interface. The method retains the same name and interface, but has a new implementation. The method declaration and implementation in the superclass is not affected when you redefine the method in a subclass. The implementation of the redefinition in the subclass obscures the original implementation in the superclass. ,ny 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 !e-3. If, for e"ample, a superclass method !& contains a call CALL METHOD 4!e-35!', and !' is redefined in a subclass, calling !& from an instance of the subclass will cause the original method !' to be called, and calling !& from an instance of the subclass will cause the redefined method !' to be called. .ithin a redefine method, you can use the pseudoreference su"er-3 to access the obscured method. This enables you to use the e"isting function of the method in the superclass without having to recode it in the subclass.
contain references to instances of any of its subclasses. In particular, you can define the target variable with reference to the generic class O$%ECT. .hen you create an object using the CREATE O$%ECT statement and a reference variable typed with reference to a subclass, you can use the TYPE addition to create an instance of a subclass, to which the reference in the reference variable will then point. , static user can use a reference variable to address the components visible to it in the superclass to which the reference variable refers. 2owever, it cannot address any speciali7ation implemented in the subclass. If you use a dynamic method call, you can address all components of the class. If you redefine an instance method in one or more subclasses, you can use a single reference variable to call different implementations of the method, depending on the position in the inheritance tree at which the referenced object occurs. This concept that different classes can have the same interface and therefore be addressed using reference variables with a single type is called polymorphism.
!nstance Constructors
4very class has an instance constructor called constructor. This is an e"ception to the rule that states that component names within an inheritance tree must be uni/ue. 2owever, the instance constructors of the various classes in an inheritance tree are fully independent of one another. 5ou cannot redefine the instance constructor of a superclass in a subclass, neither can you call one
specifically using the statement CALL METHOD CONSTR.CTOR. $onse/uently, no naming conflicts can occur. The instance constructor of a class is called by the system when you instantiate the class using CREATE O$%ECT. +ince a subclass contains all of the visible attributes of its superclasses, which can also be set by instance constructors, the instance constructor of a subclass has to ensure that the instance constructors of all of its superclasses are also called. To do this, the instance constructor of each subclass must contain a CALL METHOD S.PER-3CONSTR.CTOR statement. The only e"ception to this rule are direct subclasses of the root node O$%ECT. In superclasses without an e"plicitly-defined instance constructor, the implicit instance constructor is called. This automatically ensures that the instance constructor of the immediate superclass is called. .hen you call an instance constructor, you must supply values for all of its non-optional interface parameters. There are various ways of doing this:
#f the class that 'ou are instantiating has an instance constructor )ith an interface, 'ou must pass %alues to it using E&PORT#"'& #f the class that 'ou are instantiating has an instance constructor )ithout an interface, 'ou do not pass an' parameters& #f the class 'ou are instantiating does not ha%e an e/plicit instance constructor, 'ou must loo( in the inheritance tree for the ne/t0highest superclass )ith an e/plicit instance constructor& #f this has an interface, 'ou must suppl' %alues using E&PORT#"'& Other)ise, 'ou do not ha%e to pass an' %alues& 1sing CALL .ET1OD %UPER8ACO"%TRUCTOR
#f the direct superclass has an instance constructor )ith an interface, 'ou must pass %alues to it using E&PORT#"'& #f the direct superclass has an instance constructor )ithout an interface, 'ou do not pass an' parameters& #f the direct superclass does not ha%e an e/plicit instance constructor, 'ou must loo( in the inheritance tree for the ne/t0highest superclass )ith an e/plicit instance constructor& #f this has an interface, 'ou must suppl' %alues using E&PORT#"'& Other)ise, 'ou do not ha%e to pass an' %alues&
In both CREATE O$%ECT and CALL METHOD S.PER-3CONSTR.CTOR, you must look at the ne"tavailable e"plicit instance constructor and, if it has an interface, pass values to it. The same applies to e"ception handling for instance constructors. .hen you work with inheritance, you need an precise knowledge of the entire inheritance tree. .hen you instantiate a class at the bottom of the inheritance tree, you may need to pass parameters to the constructor of a class that is much nearer the root node. The instance constructor of a subclass is divided into two parts by the CALL METHOD S.PER3CONSTR.CTORstatement. In the statements before the call, the constructor behaves like a static method, that is, it cannot access the instance attributes of its class. 5ou cannot address instance attributes until after the call. 0se the statements before the call to determine the actual parameters for the interface of the instance constructor of the superclass. 5ou can only use static attributes or local data to do this.
.hen you instantiate a subclass, the instance constructors are called hierarchically. The first nesting level in which you can address instance attributes is the highest-level superclass. .hen you return to the constructors of the lower-level classes, you can also successively address their instance attributes. In a constructor method, the methods of the subclasses of the class are not visible. If an instance constructor calls an instance method of the same class using the implicit self-reference !e-3, the method is called as it is implemented in the class of the instance constructor, and not in any redefined form that may occur in the subclass you want to instantiate. This is an e"ception to the rule that states that when you call instance methods, the system always calls the method as it is implemented in the class to whose instance the reference is pointing.
Static Constructors
4very class has a static constructor called class_constructor. ,s far as the namespace within an inheritance tree, the same applies to static constructors as to instance constructors. The first time you address a subclass in a program, its static constructor is e"ecuted. 2owever, before it can be e"ecuted, the static constructors of all of its superclasses must already have been e"ecuted. , static constructor may only be called once per program. Therefore, when you first address a subclass, the system looks for the ne"t-highest superclass whose static constructor has not yet been e"ecuted. It e"ecutes the static constructor of that class, followed by those of all classes between that class and the subclass you addressed.
Inheritance' O er ie$
The left-hand part of the graphic shows how you can derive a subclass c' from a superclass c& using the INHERTIN, FROM addition in the CLASS statement. The right-hand part of the graphic shows the distribution of the subclass in the inheritance tree, which stretches back to the default empty class O$%ECT. , subclass contains all of the components declared above it in the inheritance tree, and can address all of them that are declared public or protected.
Single Inheritance
This graphic illustrates single inheritance. , class may only have one direct superclass, but it can have more than one direct subclass. The empty class O$%ECT is the root node of every inheritance tree in ,*,- !bjects.
This graphic shows how reference variables defined with reference to a superclass can point to objects of subclasses. The object on the right is an instance of the class class6. The class reference variables CREF&, CREF', and CREF6 are typed with reference to class&, class', and class6. ,ll three can point to the object. 2owever, CREF& can only address the public components of class&. CREF' can address the public components of class& and class'. CREF6 can address the public components of all of the classes. If you redefine a method of a superclass in a subclass, you can use a reference variable defined with reference to the superclass to address objects with different method implementations. .hen you address the superclass, the method has the original implementation, but when you address the subclass, the method has the new implementation. 0sing a single reference variable to call identicallynamed methods that behave differently is called polymorphism.
REPORT demo_in6erit*nce. CLA%% counter DE!#"#T#O". PUBL#C %ECT#O". .ET1OD%2 (et #.PORT#"' )*+ue3(et_)*+ue4 TYPE i5 increment5 get E&PORT#"' )*+ue3get_)*+ue4 TYPE i. PROTECTED %ECT#O". DATA count TYPE i. E"DCLA%%.
CLA%% counter #.PLE.E"TAT#O". .ET1OD (et. count , (et_)*+ue. E"D.ET1OD. .ET1OD increment. ADD 0 TO count. E"D.ET1OD. .ET1OD get. get_)*+ue , count. E"D.ET1OD. E"DCLA%%. CLA%% counter_ten DE!#"#T#O" #"1ER#T#"' !RO. counter. PUBL#C %ECT#O". .ET1OD% increment REDE!#"#T#O". DATA count_ten. E"DCLA%%. CLA%% counter_ten #.PLE.E"TAT#O". .ET1OD increment. DATA modu+o TYPE i. CALL .ET1OD (uper8Aincrement. Jrite F count. modu+o , count mod 0:. #! modu+o , :. count_ten , count_ten D 0. Jrite count_ten. E"D#!. E"D.ET1OD. E"DCLA%%. DATA2 count TYPE RE! TO counter5 number TYPE i VALUE . %TART8O!8%ELECT#O". CREATE OBJECT count TYPE counter_ten. CALL .ET1OD count8A(et E&PORT#"' (et_)*+ue , number. DO ;: T#.E%. CALL .ET1OD count8Aincrement. E"DDO. The class counter_ten is deri%ed from counter& #t redefines the method increment& To do this, 'ou must change the %isibilit' of the count attribute from PR#VATE to PROTECTED& The redefined method calls the obscured method of the superclass using the pseudoreference (uper8A& The redefined method is a speciali3ation of the inherited method& The e/ample instantiates the subclass& The reference %ariable pointing to it has the t'pe of the superclass& When the #"CRE.E"T method is called using the superclass reference, the s'stem e/ecutes the redefined method from the subclass&
Interfaces
$lasses, their instances (objects , and access to objects using reference variables form the basics of ,*,- !bjects. These means already allow you to model typical business applications, such as customers, orders, order items, invoices, and so on, using objects, and to implement solutions using ,*,- !bjects. 2owever, it is often necessary for similar classes to provide similar functions that are coded differently in each class but which should provide a uniform point of contact for the user. &or e"ample, you might have two similar classes, savings account and check account, both of which have a method for calculating end of year charges. The interfaces and names of the methods are the same, but the actual implementation is different. The user of the classes and their instances must also be able to run the end of year method for all accounts, without having to worry about the actual type of each individual account. ,*,- !bjects makes this possible by using interfaces. Interfaces are independent structures that you can implement in a class to e"tend the scope of that class. The class-specific scope of a class is defined by its components and visibility sections. The public components of a class define its public scope, since all of its attributes and method parameters can be addressed by all users. Interfaces e"tend the scope of a class by adding their own components to its public section. This allows users to address different classes across different inheritance trees via a universal point of contact. Interface references allow users to address and use different classes in e"actly the same way. Interfaces, along with inheritance, provide one of the pillars of polymorphism, since they allow a single method within an interface to behave differently in different classes.
(efining Interfaces
6ike classes, you can define interfaces either globally in the 'epository or locally in an ,*,- program. &or information about how to define local interfaces, refer to the $lass *uilder section of the ,*,.orkbench Tools documentation. The definition of a local interface #nt is enclosed in the statements: I;T4'&,$4 intf. ... 4;:I;T4'&,$4. The definition contains the declaration for all components (attributes, methods, events of the interface. 5ou can define the same components in an interface as in a class. The components of interfaces do not have to be assigned individually to a visibility section, since they automatically belong to the public section of the class in which the interface is implemented. Interfaces do not have an implementation part, since their methods are implemented in the class that implements the interface.
Implementing Interfaces
0nlike classes, interfaces do not have instances. Instead, interfaces are implemented by classes. To implement an interface in a class, use the statement I;T4'&,$4+ intf. in the declaration part of the class. This statement may only appear in the public section of the class.
.hen you implement an interface in a class, the components of the interface are added to the other components in the public section. , component #co!" of an interface #nt can be addressed as though it were a member of the class under the name #nt K#co!". The class must implement the methods of all interfaces implemented in it. The implementation part of the class must contain a method implementation for each interface method #!et/: 34T2!: intfKimeth. ... 4;:34T2!:. Interfaces can be implemented by different classes. 4ach of these classes is e"tended by the same set of components. The methods of the interface can be implemented differently in each class. 2owever, each class should keep the semantics of the interface. , method implementation should provide precisely that functionality which is re/uired by the interface. Interfaces allow you to use different classes in a uniform way using interface references (polymorphism . &or e"ample, interfaces that are implemented in different classes e"tend the public scope of each class by the same set of components. If a class does not have any class-specific public components, the interfaces define the entire public face of the class.
Interface References
'eference variables allow you to access objects (refer to .orking with !bjects . Instead of creating reference variables with reference to a class, you can also define them with reference to an interface. This kind of reference variable can contain references to objects of classes that implement the corresponding interface. To define an interface reference, use the addition TYPE REF TO #nt in the TYPES or DATA statement. #nt must be an interface that has been declared to the program before the actual reference declaration occurs. , reference variable with the type interface reference is called an interface reference variable, or interface reference for short. ,n interface reference #re allows a user to use the form #re -3#co!" to address all visible interface components #co!" of the object to which the object reference is pointing. It allows the user to access all of the components of the object that were added to its definition by the implementation of the interface.
This creates an instance of the class classto which the reference in #re points. If the interface #nt contains an instance attribute attr and an instance method !et/, you can address the interface components as follows: 0sing the class reference ariable cre :
To access an attribute *ttr< cref0DintfGattr To call a method met6< /A66 M9T;O7 cref.AintfBmeth
To access an attribute *ttr< iref.Aattr To call a method met6< /A66 M9T;O7 iref.Ameth
,s far as the static components of interfaces are concerned, you can only use the interface name to access constants: To access a constant const: #nt ,-const &or all other static components of an interface, you can only use object references or the class class that implements the interface: To access a static attribute attr: class,-intf.attr To call a static method !et/: C!LL "E#*O( class,-intf.meth
Nesting Interfaces
5ou can nest interfaces. ,n interface can contain one or more interfaces as its components, and these interfaces can, in turn, themselves contain interfaces. ,n interface which contains another interface is called a nested or a compound interface. ,n interface which is contained in another interface is referred to as the component interface. ,n interface which does not contain any nested interfaces is called an elementary interface. ,ll interface components of a nested interface are on the same level. If a nested interface #6 contains the interface components #' which are themselves nested and contain the interface components #&, then the components #& become interface components of #6. 1enerally, a nested interface contains each interface component e"actly once. 4ven if a component interface is used a second time as the component of another component interface, it still e"ists only once. If you want to nest interfaces, use the statement INTERFACES in an interface definition: I;T4'&,$4 i(. ... I;T4'&,$4+: i), i8 ... ... 4;:I;T4'&,$4. 2ere, the interface #6 consists of its components as well as of the interfaces #& and #'. The components of the component interfaces are not directly visible in the nested interface. In the above
definition of #6, e"pressions like #&7co!" or #'7co!"cannot be used, with the e"ception of the ALIAS statement. There are several ways how you can use the components of component interfaces:
0se: :,T,: cref T5-4 '4& T! class. ... cref-Ai)Kcomp) ... ... cref-Ai8Kcomp8 ... ... cref-Ai(Kcomp( ... ;ested e"pressions such as cre -3#67#'7co!"' or cre -3#67#'7#67co!"6 are not possible. The nesting hierarchy is only important when you assign interface references to each other. 5ou can assign class references for classes which implement a nested interface to all interface references typed with reference to an interface component contained. The interface references only know the components of their interface within the class.
The concepts of interfaces and of inheritance are completely orthogonal. In the classes of an inheritance tree you can implement as many interfaces as re/uired. 2owever, you must pay attention to the fact that each interface can be implemented only once per inheritance tree. This ensures that each interface component has a uni/ue name #nt 7#co!" across the entire inheritance tree and is contained in all subclasses starting with the class that implements the interface. Interface references that can point to a class of an inheritance tree can also point to all subclasses. !nce they have been implemented, interface methods are fully-fledged components of a class and can be redefined in subclasses. 2owever, you cannot declare interface methods as abstract or final in the definition of the interface.
See also
!verview 1raphics Interfaces: Introductory 4"ample
The left0hand side of the diagram sho)s the definition of a local interface #0 and the declaration and implementation parts of a local class C0 that implements the interface #0 in its 8ublic section& The interface method #0K.0is implemented in the implementation part of the class& .ou cannot implement interfaces in the other %isibilit' sections& The right0hand side illustrates the structure of the class )ith the components in their respecti%e %isibilit' areas, and the implementation of the methods& The interface components e/tend the public scope of the class& All users can access the public components specific to the class and those of the interface&
Classes can implement any n!mber f interfaces in their p!blic secti n. The left/han% si%e f the %ia#ram sh ws the %eclarati n an% implementati n part f a l cal class C1& which implements several interfaces in its p!blic secti n. The class m!st implement all f the interface meth %s in its implementati n part. The ri#ht/han% si%e ill!strates the str!ct!re f the class with the c mp nents in their respective visibility areas& an% the implementati n f the meth %s. The interface c mp nents e.ten% the p!blic secti n f the class in which they are %eclare%.
REPORT demo_interf*ce. #"TER!ACE (t*tu(. .ET1OD% Jrite. E"D#"TER!ACE. CLA%% counter DE!#"#T#O". PUBL#C %ECT#O". #"TER!ACE% (t*tu(. .ET1OD% increment.
PR#VATE %ECT#O". DATA count TYPE i. E"DCLA%%. CLA%% counter #.PLE.E"TAT#O". .ET1OD (t*tu(KJrite. /R#TE2 F $Count in counter i($5 count. E"D.ET1OD. .ET1OD increment. ADD 0 TO count. E"D.ET1OD. E"DCLA%%. CLA%% bic7c+e DE!#"#T#O". PUBL#C %ECT#O". #"TER!ACE% (t*tu(. .ET1OD% dri)e. PR#VATE %ECT#O". DATA (peed TYPE i. E"DCLA%%. CLA%% bic7c+e #.PLE.E"TAT#O". .ET1OD (t*tu(KJrite. /R#TE2 F $%peed of bic7c+e i($5 (peed. E"D.ET1OD. .ET1OD dri)e. ADD 0: TO (peed. E"D.ET1OD. E"DCLA%%. The interface (t*tu( contains one method called Jrite& The classes counter and bic7+eimplement the interface in the public section& Both classes must implement the interface method in their implementation part in accordance )ith the semantics re-uired& The follo)ing sections e/plain ho) a user can use interface references to address the objects of both classes<
Example
First& tw class reference variables CREF1 an% CREF4 are %eclare% f r the classes C_COUNTER1 an% C_COUNTER4. An interface reference 3REF is als %eclare% f r the interface 3_COUNTER. All f the reference variables are initial.
Example
The CREATE O'(ECT statement creates an b)ect f r each class t which the references in CREF1 an% CREF4 p int.
Example
;hen the reference f CREF1 is assi#ne% t 3REF& the reference in 3REF als p ints t the b)ect with the internal name C_COUNTER,1-.
#riggering E ents
To trigger an event, a class must
eclare the e%ent in its declaration part Trigger the e%ent in one of its methods
Declaring E$ents
5ou declare events in the declaration part of a class or in an interface. To declare instance events, use the following statement: 4>4;T+ evt 4H-!'TI;1... >,604(e) e8 ... T5-4 type C!-TI!;,6D.. To declare static events, use the following statement:
$6,++-4>4;T+ evt... *oth statements have the same synta". .hen you declare an event, you can use the E-PORTIN,addition to specify parameters that are passed to the event handler. The parameters are always passed by value. Instance events always contain the implicit parameter SENDER, which has the type of a reference to the type or the interface in which the event is declared.
riggering E$ents
,n instance event in a class can be triggered by any instance method in the class. +tatic events can be triggered by any method. 2owever, static methods can only trigger static events. To trigger an event in a method, use the following statement: ',I+4 4>4;T evt 4H-!'TI;1 e) E f) e8 E f8 ... &or each formal parameter e& that is not defined as optional, you must pass a corresponding actual parameter & in the E-PORTIN, addition. The self-reference !e is automatically passed to the implicit parameter sen0er.
*andling E ents
4vents are handled using special methods. To handle an event, a method must
be defined as an e%ent handler method for that e%ent be registered at runtime for the e%ent&
An instance e%ent declared in a class An instance e%ent declared in an interface A static e%ent declared in a class A static e%ent declared in an interface
The synta" and effect of the SET HANDLERdepends on which of the four cases listed above applies. &or an instance event, you must use the FOR addition to specify the instance for which you want to register the handler. 5ou can either specify a single instance as the trigger, using a reference variable re : +4T 2,;:64' h) h8 ... &!' ref. or you can register the handler for all instances that can trigger the event: +4T 2,;:64' h) h8 ... &!' ,66 I;+T,;$4+. The registration then applies even to triggering instances that have not yet been created when you register the handler. 5ou cannot use the FOR addition for static events: +4T 2,;:64' h) h8 ... The registration applies automatically to the whole class, or to all of the classes that implement the interface containing the static event. In the case of interfaces, the registration also applies to classes that are not loaded until after the handler has been registered.
See also' 4vents: !verview 1raphic 4vents: Introductory 4"ample 4vents: $omple" 4"ample
The class C0 contains an e%ent E0, )hich is triggered b' the method .0& Class C; contains a method .;, )hich can handle e%ent E0 of class C0& The follo)ing diagram illustrates handler registration<
The program creates an instance of the class C0 and t)o instances of the class C;& The %alues of the reference %ariables R0, 10, and 1; point to these instances& The %ET 1A"DLER statement creates a handler table, in%isible to the user, for each e%ent for )hich a handler method has been registered& The handler table contains the names of the handler methods and references to the registered instances& The entries in the table are administered d'namicall' b' the %ET 1A"DLERstatement& A reference to an instance in a handler table is li(e a reference in a reference %ariable& #n other )ords, it counts as a use of the instance, and therefore directl' affects its lifetime& #n the abo%e diagram, this means that the instances C;E0A and C;E;A are not deleted b' the garbage collection, e%en if H8 and HH are initiali3ed, so long as their registration is not deleted from the handler table& For static e%ents, the s'stem creates an instance0independent handler table for the rele%ant class&
When an e%ent is triggered, the s'stem loo(s in the corresponding e%ent table and e/ecutes the methods in the appropriate instances *or in the corresponding class for a static handler method+&
REPORT demo_c+*((_counter_e)ent. CLA%% counter DE!#"#T#O". PUBL#C %ECT#O". .ET1OD% increment_counter. EVE"T% critic*+_)*+ue E&PORT#"' )*+ue3eGce((4 TYPE i. PR#VATE %ECT#O". DATA2 count TYPE i5 t6re(6o+d TYPE i VALUE 0:. E"DCLA%%. CLA%% counter #.PLE.E"TAT#O". .ET1OD% increment_counter. DATA diff TYPE i. ADD 0 TO count. #! count A t6re(6o+d. diff , count 8 t6re(6o+d. RA#%E EVE"T critic*+_)*+ue E&PORT#"' eGce(( , diff. E"D#!. E"D.ET1OD. E"DCLA%%. CLA%% 6*nd+er DE!#"#T#O". PUBL#C %ECT#O". .ET1OD% 6*nd+e_eGce(( !OR EVE"T critic*+_)*+ue O! counter #.PORT#"' eGce((. E"DCLA%%. CLA%% 6*nd+er #.PLE.E"TAT#O". .ET1OD 6*nd+e_eGce((. /R#TE2 F $EGce(( i($5 eGce((. E"D.ET1OD. E"DCLA%%. DATA2 r0 TYPE RE! TO counter5 60 TYPE RE! TO 6*nd+er. %TART8O!8%ELECT#O". CREATE OBJECT2 r05 60.
%ET 1A"DLER 608A6*nd+e_eGce(( !OR ALL #"%TA"CE%. DO ;: T#.E%. CALL .ET1OD r08Aincrement_counter. E"DDO. The class counter implements a counter& #t triggers the e%ent critic*+_)*+ue )hen a threshold %alue is e/ceeded, and displa's the difference& 6*nd+ercan handle the e/ception in counter& uring runtime, the handler is registered for all reference %ariables that point to the object&
O er ie$
This object works with the interactive list displayed below. 4ach user interaction triggers an event in ,*,- !bjects. The list and its data is created in the class c_l#st. There is a class status for processing user actions. It triggers an event 1utton_cl#c8e0in the AT .SER-COMMAND event. The event is handled in the class c_l#st. It contains an object of the class c_sHIP or c_truc8for each line of the list. *oth of these classes implement the interface #_ve/#cle. .henever the speed of one of these objects changes, the event s"ee0_c/an9e is triggered. The class c_l#streacts to this and updates the list.
Constraints
The ABAP statements used for list processing are not 'et full' a%ailable in ABAP Objects& Ho)e%er, to produce a simple test output, 'ou can use the follo)ing statements<
=ote< The beha%ior of formatting and interacti%e list functions in their current state are not guaranteed& #ncompatible changes could occur in a future release&
(eclarations
This e"ample is implemented using local interfaces and classes. *elow are the declarations of the interfaces and classes: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: : Inter ace an0 class 0eclarat#ons ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: INTERFACE #_ve/#cle* DATA !a+_s"ee0 TYPE #*
EVENTS s"ee0_c/an9e E-PORTIN, VAL.E;ne<_s"ee0= TYPE #* METHODS> 0r#ve? sto"* ENDINTERFACE* :---------------------------------------------------------------CLASS c_s/#" DEFINITION* P.$LIC SECTION* METHODS constructor* INTERFACES #_ve/#cle* PRIVATE SECTION* ALIASES !a+ FOR #_ve/#cle7!a+_s"ee0* DATA s/#"_s"ee0 TYPE #* ENDCLASS* :---------------------------------------------------------------CLASS c_truc8 DEFINITION* P.$LIC SECTION* METHODS constructor* INTERFACES #_ve/#cle* PRIVATE SECTION*
ALIASES !a+ FOR #_ve/#cle7!a+_s"ee0* DATA truc8_s"ee0 TYPE #* ENDCLASS* :---------------------------------------------------------------CLASS status DEFINITION* P.$LIC SECTION* CLASS-EVENTS 1utton_cl#c8e0 E-PORTIN, VAL.E; co0e= LI@E s2-uco!!* CLASS-METHODS> class_constructor? user_act#on* ENDCLASS* :---------------------------------------------------------------CLASS c_l#st DEFINITION* P.$LIC SECTION* METHODS> co0e_/an0ler FOR EVENT 1utton_cl#c8e0 OF status IMPORTIN, co0e? l#st_c/an9e FOR EVENT s"ee0_c/an9e OF #_ve/#cle IMPORTIN, ne<_s"ee0? l#st_out"ut*
PRIVATE SECTION* DATA> #0 TYPE #? re _s/#" TYPE REF TO c_s/#"? re _truc8 TYPE REF TO c_truc8? $E,IN OF l#ne? #0 TYPE I? la9;&= TYPE c? #re TYPE REF TO #_ve/#cle? s"ee0 TYPE #? END OF LINE? LIST LI@E SORTED TA$LE OF l#ne AITH .NIB.E @EY #0* ENDCLASS* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
The class c_l#st contains event handler methods for both events. ;ote that the class status does not have any attributes, and therefore only works with static methods and events.
Implementations
*elow are the implementations of the methods of the above classes: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: : I!"le!entat#ons ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: CLASS c_s/#" IMPLEMENTATION* METHOD constructor* !a+ ) 6C* ENDMETHOD* METHOD #_ve/#cle70r#ve* CHEC@ s/#"_s"ee0 D !a+* s/#"_s"ee0 ) s/#"_s"ee0 E &C* RAISE EVENT #_ve/#cle7s"ee0_c/an9e E-PORTIN, ne<_s"ee0 ) s/#"_s"ee0* ENDMETHOD* METHOD #_ve/#cle7sto"* CHEC@ s/#"_s"ee0 3 C* s/#"_s"ee0 ) C* RAISE EVENT #_ve/#cle7s"ee0_c/an9e E-PORTIN, ne<_s"ee0 ) s/#"_s"ee0* ENDMETHOD* ENDCLASS* :---------------------------------------------------------------CLASS c_truc8 IMPLEMENTATION* METHOD constructor* !a+ ) &FC* ENDMETHOD* METHOD #_ve/#cle70r#ve* CHEC@ truc8_s"ee0 D !a+* truc8_s"ee0 ) truc8_s"ee0 E FC* RAISE EVENT #_ve/#cle7s"ee0_c/an9e E-PORTIN, ne<_s"ee0 ) truc8_s"ee0* ENDMETHOD* METHOD #_ve/#cle7sto"* CHEC@ truc8_s"ee0 3 C* truc8_s"ee0 ) C* RAISE EVENT #_ve/#cle7s"ee0_c/an9e
ENDMETHOD* ENDCLASS*
:---------------------------------------------------------------CLASS status IMPLEMENTATION* METHOD class_constructor* SET " -status GVEHICLEG* ARITE GCl#c8 a 1uttonHG* ENDMETHOD* METHOD user_act#on* RAISE event 1utton_cl#c8e0 E-PORTIN, ENDMETHOD* ENDCLASS* :---------------------------------------------------------------CLASS c_l#st IMPLEMENTATION* METHOD co0e_/an0ler* CLEAR l#ne* CASE co0e* AHEN GCREA_SHIPG* #0 ) #0 E &* CREATE O$%ECT re _s/#"* l#ne-#0 ) #0* l#ne- la9 ) GcG* l#ne-#re ) re _s/#"* APPEND l#ne TO l#st* AHEN GCREA_TR.C@G* #0 ) #0 E &* CREATE O$%ECT re _truc8* l#ne-#0 ) #0* l#ne- la9 ) GTG* l#ne-#re ) re _truc8* APPEND l#ne TO l#st* AHEN GDRIVEG* CHEC@ s2-l#ll# 3 C* READ TA$LE l#st INDE- s2-l#ll# INTO l#ne* CALL METHOD l#ne-#re -30r#ve* AHEN GSTOPG* LOOP AT l#st INTO l#ne* CALL METHOD l#ne-#re -3sto"* ENDLOOP* AHEN GCANCELG* LEAVE PRO,RAM* ENDCASE* CALL METHOD l#st_out"ut* ENDMETHOD* METHOD l#st_c/an9e* l#ne-s"ee0 ) ne<_s"ee0* co0e ) s2-uco!!*
MODIFY TA$LE l#st FROM l#ne* ENDMETHOD* METHOD l#st_out"ut* s2-ls#n0 ) C* SET TITLE$AR GTITG* LOOP AT l#st INTO l#ne* IF l#ne- la9 ) GCG* ARITE I #con_<s_s/#" AS #con* ELSEIF l#ne- la9 ) GTG* ARITE I #con_<s_truc8 AS #con* ENDIF* ARITE> GS"ee0 ) G? l#ne-s"ee0* ENDLOOP* ENDMETHOD* ENDCLASS* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
The static method user_act#on of the class status triggers the static event 1utton_cl#c8e0. The instance methods #_ve/#cle70r#ve and #_ve/#cle7sto" trigger the instance event #_ve/#cleKs"ee0_c/an9e in the classes c_s/#" and c_truc8.
The program creates an object of the class c_l#stand registers the event handler method co0e_/an0ler of the object for the class event 1utton_cl#c8e0, and the event handler method l#st_c/an9e for the event s"ee0_c/an9e of all instances that implement the interface #_ve/#cle.
$lass pools contain a definition part for type declarations, and the declaration and implementation parts of the class.
ABAP programs such as e/ecutable programs, module pools, or function modules, usuall' ha%e a declaration part in )hich the global data for the program is defined& This data is %isible in all of the processing bloc(s in the program& Class pools, on the other hand, ha%e a definition part in )hich 'ou can define data and object t'pes, but no data objects or field s'mbols& The t'pes that 'ou define in a class pool are onl, %isible in the implementation part of the global class& The onl' processing bloc(s that 'ou can use are the declaration part and implementation part of the global class& The implementation part ma' onl' implement the methods declared in the global class& .ou cannot use an' of the other ABAP processing bloc(s *dialog modules, e%ent bloc(s, subroutines, function modules+& The processing bloc(s of class pools are not controlled b' the ABAP runtime en%ironment& =o e%ents occur, and 'ou cannot call an' dialog modules or procedures& Class pools ser%e e/clusi%el' for class programming& .ou can onl' access the data and functions of a class using its interface& "ince e%ents and dialog modules are not permitted in classes, 'ou cannot process screens in classes& .ou cannot program lists and selection screens in classes, since the' cannot react to the appropriate
e%ents& #t is intended to ma(e screens a%ailable in classes& #nstead of dialog modules, it )ill be possible to call methods of the class from the screen flo) logic&
OO Transactions
#n transaction maintenance *"$I7+, 'ou can specif' a transaction code as an OO transaction& .ou either lin( the transaction code to the Transaction "er%ice of the ABAP Object "er%ices for persistent objects or to a public method of a global or local class of a program& When calling up a transaction that is lin(ed to an instance method, the s'stem automaticall' generates an instance of the class in its o)n internal session& An e/ample of a lin( bet)een a transaction code and an instance method of a local class of an unspecified ABAP program<
9L888888888888888888888888888888888888888888888888888888888889 9L .odu+e poo+ DE.O_OO_TRA"%ACT#O" 9 9L 9 9L888888888888888888888888888888888888888888888888888888888889 progr*m DE.O_OO_TRA"%ACT#O". c+*(( DE.O_CLA%% definition. pub+ic (ection. met6od( #"%TA"CE_.ET1OD. endc+*((. c+*(( DE.O_CLA%% imp+ement*tion. met6od #"%TA"CE_.ET1OD. me((*ge $#n(t*nce met6od in +oc*+ c+*(($ t7pe $#$. endmet6od. endc+*((. The DE.O_OO_TRA"%ACT#O" program is a module pool that does not contain an' screens or dialog modules& #nstead, the program contains the definition of a local class DE.O_CLA%%& The DE.O_OO_.ET1OD transaction code is lin(ed to this program as follo)s< The start object of the transaction is Method of a class (OO transaction). OO transaction model is not selected&
The Class Name is DE.O_CLA%%& The Method is #"%TA"CE_.ET1OD& Local in program is selected and DE.O_OO_TRA"%ACT#O" specified& When the transaction is called up, the program is loaded, an instance of the class is created, and the method is e/ecuted&