You are on page 1of 113
Public attributes are defined in the PUBLIC section and can be viewed and changed from outside the clase. There is direct access to public atributes. As © general rule, as few public attributes should be defined as poss ble Private attributes Private atibuies are defined in the PRIVATE section. The can only be viewes and changed from within the clase, There is ne direct secees from outee the class. Instance attributes There exist one instance attribute for each instance of the class, thus they exist seperately for each object. Instance attibutee are declared with the DATA keyword, Static attributes Static attributes exist only once for each class. The data ate the same for all instances of the clate, and can be used e.g, forinstance courters. Static atiioutes are defined with the keyword CLASS-DATA (CLASS-DATA: counter pe Public methods Can called from outside the class ETHODS: set strbutbs IMPORTING p_name 25) TYPE c, _plaetipe LIKE capiene-plonetp Private methods: Can only be called irom inside the class. They are placed in the PRIVATE section ofthe claes Public attributes Public attributes are defined in the PUBLIC section and can be viewed and changed from outside the class. There is direct access to public attributes. As a general rule, as few public attributes should be defined as possible. PUBLIC Private attributes Private attributes are defined in the PRIVATE section. The can only be viewes and changed from within the class. There is no direct access from outside the class. PRIVATE SECTION Dat : name (25) TYPE cy planetype LIKE saplane-planetyp, Instance attributes There exist one instance attribute for each instance of the class, thus they exist seperately for each object. Instance attributes are declared with the DATA keyword. Static attributes Static attributes exist only once for each class. The data are the same for all instances of the class, and can be used e.g. for instance counters. Static attributes are defined with the keyword CLASS-DATA. PRIVATE SECTION, CLASS-DATA: counter type i, Public methods Can called from outside the class PUBLIC SECTION. METHODS: set_attributes IMPORTING p_name(25) TYPE c, p_planetype LIKE saplane-planetyp, Private methods Can only be called from inside the class. They are placed in the PRIVATE section of the class. Constructor method Impiiity, each class has an insiance constructor method with the reserved name ‘constructor and a etatie conetiuctor method with the reserved name class_constructor, The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statoment, whilo the class constructor is executed ‘exactly once belore you first access a class. The constructors are always present. However, to implement a constructor you must declare it exateitly with the METHODS er CLASS-METHODS statements. [An instance constructor can have IMPORTING parameters and exceptions. You ‘must pase all non-optional parametats when creating an object. Stale constructors have no parameters. Static constructor The statie constructor is always called CLASS_CONSTRUCTER, and is called autmateally before the of ie fret accessed, that ie bafore any of the following actions are executed! Creating an Instance using GREATE_OBJECT Adressing a state attibute using -> + Calling a ststic attribute using CALL METHOD + Registering a static event handler + Registering an evetm handler method for a static event The static constructor cannot be called explicitly. Protected components When we are talking subclassing and enheritance there is one more component than Public and Private, the Protected component. Protected components can be used by the superclass and all of the subclasses. Note that Subclasses cannot access Private components. Polymorphism Polymorphism: When the same method is implemented differently in different classes. This can be done using enheritance, by redefining a method from the superclass in subclasses and implement it differently. ‘Template for making a class Delete the parts that should not be used Template for making a class Delete the parts that should not be used ENON renninreneinnnneresesinenssenine © Definition part Anda atebanadenadauaneuananenaaueaeuenede CLASS xXx DEFINITION. * Public section * PUBLIC SECTTON. TYPES: DATA: * Static data CLASS-DATA: * Methods METHODS: * Using the constructo: IMPORTING xxx type yyy, to initialize parameters constructor * Method with parameters ml IMPORTING iii TYPE * Method without parameters mn2. * Static methods CLASS-METHODS: + * Protected section Also accessable by subclasses *~ PROTECTED SECTION. Private section, Not accessable by subclasses *-~ PRIVATE SECTION. ENDCLASS. sdnunuauauauausuaesesessaesesusesesesesess © Implementation part eeietetehenernenstennrsesttentceseetees CLASS lel alzplane IMPLEMENTATION. METHOD constructor. ENDMETHOD. METHOD mm. ENDMETHOD. METHOD mm2. ENDMETHOD. ENDCLASS. ‘Template for calling a class Subelas: lao: hod meTHoDs: ‘edad_e_new_airplane importing im_airplane TYPE REF te lel airplane Interfaces In ARAP inlertaces a implemented in additon . and indepardemiy ol cease. An interlace cn hoa dcolaton pat and de ro! Mave viebillty cectione Components (tebulee, methods cormlants, pes) eae defined the sare way os comes + Interfaces are listed in the definition pavt lof the olass, and mustalways be in the PUBLIC SECTION. + Operations defined inthe interface atte impemented ae methede of the class. All methods of the interface must be present in the + impiomentation part of tho olaee. + Atirbutes, events, constants and types defined in the intertace are automatically avaiable to the clage catying out the mpl mantaton, + Inierface components are adresse in the class by = Example of how to implemantan interface: INTERFACE _decunent DATA: author type ref to l_author ETHODS: pri, display, CLASS lel_text_document DEFINITION ‘Template for calling a class ence toc _aizplane DATA: airplanel TYPE REF TO airpl TTON. * Create instance using parameters in the cosntructor method CREATE T airplane] exporting im_name = 'Hansemand! planetype = "Boing 747*. * Calling a method with parameters CALL METHOD: airplanel->display_n_o_airplanes, airplanel->display attributes Subclass CLASS xxx DEFINITION INHERITING FROM yyy. Using af class as a parameter for a method ‘The class LCL_AIRPLANE is used as a parameter for method add_a_new_airplane: METHODS: add_a_new_airplane importing im_airplane TYPE REF to Icl_airplane. Interfaces In ABAP interfaces are implemented in addition to, and independently of classes. An interface only has a declaration part, and do not have visibility sections. Components (Attributes, methods, constants, types) can be defined the same way as in classes. + Interfaces are listed in the definition part lof the class, and must always be in the PUBLIC SECTION. + Operations defined in the interface atre impemented as methods of the class. All methods of the interface must be present in the + implementation part of the class. + Attributes, events, constants and types defined in the interface are automatically available to the class carying out the implementation. + Interface components are adresse in the class by ~ Example of how to implement an interface: INTERFACE lif_document DATA: author type ref to Icl_author. METHODS: print, display. ENDINTERFACE. CLASS Icl_text_document DEFINITION. PUBLIC SECTION. INTERFACES I4_document. METHODS — display. ENDCLASS. GLASS lel_text_document IMPLEMENTTION. METHOD lit_document- pint ENDMETHOD. METHOD lif_document-dieplay ENDMETHOD. METHOD ciepiay, ENDMETHOD. ENDCLASS. DATA: text doc TYPE REF TO bl document Start of selection, CREATE OBJECT text_doc, CALL METHOD text_dac-mii_document~rint. CALL METHOD text_doo-si_ cocumen'~diaplay, CALL METHOD toxt_doo->dioplay. Events + Events can only have EXPORTING parameters + When an event is trggerede, only those events handlers that have registred themselves using SET HANDLER by this point of runtime are + “executed. You can register an event using ACTIVATION X'and derigert i by using ACTIVATION ‘SPACE Defining events CLASS DEFINITION, EVENTS: EXPORTING VALUE (sex_par) TYPE type CLASS IMPLEMENTATION. METHOD : RAISE EVENT EXPORTING Handling evente: GLASS DEFINITION. METHODS: OF ! IMPORTING .. SENDER, Setting handler SET HANDLER FOR ! FOR ALL INSTANCES act_par>. [ACTIVATION evar] PUBLIC SECTION. INTERFACES lif_document. METHODS display. ENDCLASS. CLASS Icl_text_document IMPLEMENTTION. METHOD lif_document~print. ENDMETHOD. METHOD lif_document~display ENDMETHOD. METHOD display. ENDMETHOD. ENDCLASS. REPORT zzz. DATA: text_doc TYPE REF TO Icl_document. Start-of-selection. CREATE OBJECT text_doc. CALL METHOD text_doc->lif_document~print. CALL METHOD text_doc->lif_document~display. CALL METHOD text_doc->display. Events For events of controls, refer to How to use control. + Events can only have EXPORTING parameters + When an event is triggerede, only those events handlers that have registred themselves using SET HANDLER by this point of runtime are + executed. You can register an event using ACTIVATION ‘x’ and derigert it by using ACTIVATION ‘SPACE’. Defining events: CLASS DEFINITION. EVENTS: EXPORTING VALUE () TYPE type. CLASS IMPLEMENTATION METHOD : RAISE EVENT EXPORTING = . Handling events: CLASS DEFINITION. METHODS: FOR OF ! IMPORTING ... SENDER. Setting handler SET HANDLER FOR ! FOR ALL INSTANCES [ACTIVATION ] Define, implement and use simple class seeimcuuon necd0e_Me_Lck AIRPLANE Define, implement and use simple class **tINCLUDE ZBC404_HF_LCL_AIRPLANE . eeininneieiinrsteneiirnrtientaneestees © Definition part oon Hou nononononinonjiiariuinintiaririot CLASS lel aizplane DEFINITION. * Public section PUBLIC SECTION. TYPES: t_name(25) TYPE c. METHODS: constructor, set_attriputes IMPORTING p_name TYPE t_name p_planetype TYPE saplane-planetype, display attributes, display_n_o_aizplanes. * Pe vate section *~ PRIVATE SECTION, * Private attributes DATA: name (25) TYPE c, planetype TYPE saplane-planetype. * Private static attribute CLASS-DATA n_o airplanes TYPE i. ENDCLASS. enaeaeribabenedaiananandsaennanaedacens + Implementation part Shei oioibeietetetetttetateteeasasae#® CIASS lel_airplane TMPLEMENTATTON. METHOD constructor. * Counts number of instances airplanes = n_o airplanes + 1. =NDMBTHOD. METHOD set_attributes. name = p_name, planetype = p_planetype. ENDMBTKOD. METHOD display attributes. WRITE: / 'Name:', name, 'Planetype:', planetype. ENDMETHOD. METHOD display_n_o airplanes. WRITE: / 'No. planes n_o_airplanes. The resulting report: o.plenes No planes: 2 Nome Ka Planstyp M80 Use constructor to ereate an object with parameters ENDMETEOD, ENDCLASS. REPORT zbc404_hf_maintain_airplanes . INCLUDE zbe404_hf_1cl_airplane. * Create reference to class 1cl_airplane DAA: airplanel TYPE REF TO lel_airplane, airplane? TYPE REF TO Icl_sirplane. START-OF-SELECTION. * Create instance CREATE OBJECT aixplanel. CALL METHOD: airplanel->display_n_o airplanes. CREATE OBJECT airplane2. Lting attributes using a method with parameters CALL METHOD aizplanel->set_attributes EXPORTING p_name = ‘Kurt! p_planetype = ‘mp80" END-OF-SELECTION. * Using methods CALL MuTHOD: aizplanel->display_n_¢_aixplanes, airplanel->display attributes. The resulting report: Maintain airplanes No. planes: 4 No. planes: 2 Name: Kurt Planetype: MDBO Use constructor to create an object with parameters ‘LASS 1el_aizplane DEFINITION. PUBLIC SECTION. TYPES: t_name(25) TYPE c. MerHoDs: constructor importing p2_name type t_nane p2_planetype TYPE saplane-planetype, moze code ....... CLASS 1cl_airplane IMPLEMENTATION. METHOD constructor. name = p2_nane. ‘CREATE OBJECT aizplanel exporting pi_name = 'Hanserand’ Blplenctype = Boing 767° Subelassing This example uses a superclass LCL_AIRPLANE and subslasses it into LOL_PASSENGER.AIHPLANE and LCL_GARGO_ PLANE. LCL_AIRPLANE has a method aisplay_n_o_airlanes that dispiays the number of object instances, LOL_PASSENGER_AIRPLANE has the privaio incianes attribute n_o_seats, and redefines the superclass method dlsplay_attributes, soit also displays no_seats LOL_CARGO_PLANE has the private instaros attribute caryomax, end redofinos the Superciass method cisplay_attrbutes, so & also displays cagomax Allinstance attributes are provided by the cunstuctor method. Superciass LCL_AIRPLANE planetype = p2_planetype. more code START-0} BCTION. CREATE OBJECT airplane! exporting p2_name = 'Hansemand" p2_planetype = "Boing 747, Subclassing This example uses a superclass LCL_AIRPLANE and subclasses it into LCL_PASSENGER_AIRPLANE and LCL_CARGO_PLANE. LCL_AIRPLANE has a method display_n_o_airplanes that displays the number of object instances. LCL_PASSENGER_AIRPLANE has the private instance attribute n_o_seats, and redefines the superclass method display_attributes, so it also displays n_o_seats. LCL_CARGO_PLANE has the private instance attribute cargomax, and redefines the superclass method display_attributes, so it also displays cargomax. All instance attributes are provided by the cunstructor method Superclass LCL_AIRPLANE ***INCLUDE ZBC404_HF LCL AIRPLANE ZSERIES IONE OnE © Det ion p: Peete edesenewenadenanssanavanauuedaueneee CLASS lel airplane DEFINITION. PUBLIC SECT! DYPES: t_name(25) TYEE c. METHODS MPORTING im_name TYPE t_name im_planetype TYPE saplane-planetype, attributes. © methods CLASS-METHO! no airplanes Sub class LCL_PASSENGER_AIRPLANE canes ici_peczenger airplane OEYINZTION INMERITING FRAt Lol sazplane * Protected section * PROTECTED SECTION, * Private attributes DATA: name (25) TYPE cy planetype TYPE saplane-planetype. * Private static attribute CIASS-DATA n_o_airplanes TYPE i ENDCLASS. Sebsteseinnenensiiiensneneuaensteeseauens + Implementation part ESOn nnon in onononononononiiinininonitnn CLASS lcl_aizplane IMPLEMENTATION. METHOD constructor. im_name. planetype = im planetype. * Counts number of instances no aizplanes = no alzplanes + 1. ZNDMETHOD. METHOD display_attributes. WRITE:/ 'Name:', name, 'Planetype:', planetype. ENDMETHOD, METHOD display no airplanes. WRITE: / 'No. planes:', n_o_airplanes. ENDMETEOD. ENDCLASS. Sub class LCL_PASSENGER_AIRPLANE ‘**INCLUDE 25C404_HF_LCL_PASSENGER_PLANS, prererecececeeeecdent ces ccececcaetecereserceerecececcescetcereceseaea Tene a subclass of class 1cl_airplane irveversvenversteenreersersvecerrcrerterittrcerrertterttirerrertreaav tc lel_passenger_airplane DEFINITION INHERITING FROM lel_airplane PUBLIC SECTION. * The constructor contains the parameters from the superclass * plus the parameters from the subclass METHODS: constructor IMPORTING im name TYPE t_name im_planetype TYPE saplane-planetype im_n_o_seats TYPE sflight-seatsmax, * Redefinition of superclass method display attributes display_attributes REDEFINITION PRIVATE SECTION DATA: 7, seats TYPE sflight-seatsmax ENDCLASS. CLASS lel_passenger_airplane IMPLEMENTATION. METHOD constructor. * The constructor method of the superclass MUST be called withing the * construtor CAML METHOD super->constructor EXPORTING im name = im name im planetype = im planetype. n_o_seats o_seate. ENDMETHOD. * The redefined display_attributes method MeTHOD display_attributes. CALL METHOD super->display attributes. WRITE ENDMETEOD / 'No. seats:', n_o_seats. ENDCLASS. Sub class LCL_CARGO_PLANE ***INCLUDE 2BC404_HF_LCL_CARGO_PLANE . SCE OT no Cee EERE TERETE © This 1s a subclass of class 1cl_airplane shadaustsuanatenanaaneanagenaauaantenadehatanansianadenaneeseeeht CLASS lel_cargo_plane DEFINITION INHERITING FROM icl_airplane. PUBLIC SECTION, METHODS: * The constructor contains the parameters from the superclass * plus the parameters from the subclass constr x IMPORTING im_name TYPE t_name im planetype TYPE saplane-planetype im cargomax type seplane-cargomax, * Redefinition of superclass method display_attributes display attributes REDEFINITION. PRIVATE SECTION. DATA:cargomax TYPE scplane-cargomax. ENDCLASS. CLASS Iel_cargo_plane IMPLEMENTATION. METHOD constructor. * The constructor method of the superclass MUST be called withing the * constructor CALL METHOD super->constructor EXPORTING im_name = im_nane im_planetype = im planetype. cargomax = im_cargomax. ENDMETHOD, METHOD display attributes. * The redefined display_attributes method CALL METHOD super->display attributes. WRITE ENDMETEOD. / "Cargo max:", cargomax. ENDCLASS. The Main program that uses the classes Result: No. panes: 0 Name: LH505 Planetype: Boing 747 No, seats: 30 Name: ARS Planetype: DC 9 Cargo max: 35,0000 2 No. plans The Main program that uses the classes REPORT zbc404_hf_main . * Super class INCLUDE zbc404_hf_icl_airplane. * Sub classes INCLUDE zbe404_hf_1cl_passenger_plane. INCLUDE zbe404_hf_lcl_cargo_plane. DATA: * Type ref to sub classes. Note: Tt is not necesssary to make typeref to the superclass © passenger aizplane TYPE REF TO lcl passenger airplane, 9 cargo plane TYPE REF TO lel_cargo_plane. START-OF-SELECTION. * Display initial number of instances = 0 CALL METHOD 1cl_airplane=>display_n_o_airplanes. * Create objects CREATE OBJECT o_passencer_airplane EXPORTING im_name = 'LH505' im planetype = "Boing 747' im no seats = 350. CAEATS OBJECT ©_cargo_plane EXPORTING im_name = 'ARI3" im planetype = 'DC 3" im cargomax = 35. * Display attributes CALL METHOD © passenger _airplane->display attributes. CALL METHOD o_cargo_plane->display attributes. * Call static method display_n_o_airplanes ‘Note: The syntax for calling a superclass method, differs from the syntax when calling a subclass method. * When calling a superclass must be used instead of => CALL METHOD icl_airplane->display_n_o airplanes. Result: No, planes: 0 Name: LH505 Planetype: Boing 747 No. seats: 350 Name: AR13. Planetype: DC 3 Cargo max: 35,0000 No. planes: 2 Polymorphism Polymorphism: When the same method is implemented differently in different slazses, This can be done using enhertance, by redefining a method from the superclass in subclasses and impleme nti clfferentiy. Chsses: + bol aisplane Superciass + lcleargo_airplane Subelass + kel passenger_airplane Subclass The method estimate_iuel_consumotion is implemented differently in the 3 lasses, ae it dopends on the airplane type Object from different classes are stored in an internal table (plane_lst) ‘consisting of references to the suparclass, and the processad identicaly for all the classes What ceding fer the estimate_fuel_consumption method taht ie actually executed, depends on the dynamie type af the plane referance variable, that is, depends on which object plane points to, baTa-cargo_plane TYPE REF to Iel_cargo_airplane, passanger_plane TYPE REF to lol passanger_airplane, plane list TYPE TABLE OF REF TO [cl airplane. * Creating the list of references CREATE OBJECT eargo_plane APPEND cargo_plane to planet. OREATE OBJECT passenger_plane APPEND passenger_plane to plane list, * Generic method foi calucalting required {uel METHOD calouiate required_fuel, DATA: plane TYPE REF TO Icl_aitpiane. LOOP AT plane list INTO plane. re_fuel - re_fuel + plane->estimate_{uel_consumption( distance ) ENDLOOP. ENDMETHOD. Working example: This example assumes that the classes Icl_airplane, Icl_passnger_aicplane and Icl_cargo plane (Se Subeallsina) exists Create objects of type lel_carge_plane and lol_passenger_airplane, adds them to a list in lel_earrier, anc displays the lst. Polymorphism: When the same method is implemented differently in different classes. This can be done using enheritance, by redefining a method from the superclass in subclasses and implement it differently. Classes: + Icl_airplane Superclass *Icl_cargo_airplane Subclass + Icl_passenger_airplane Subclass The method estimate_fuel_consumption is implemented differently in the 3 classes, as it depends on the airplane type. Object from different classes are stored in an internal table (plane _list) consisting of references to the superclass, and the processed identically for all the classes. What coding for the estimate_fuel_consumption method taht is actually executed, depends on the dynamic type of the plane reference variable, that is, depends on which object plane points to. DATA: cargo_plane TYPE REF to Icl_cargo_airplane, passenger_plane TYPE REF to Icl_passenger_airplane, plane_list TYPE TABLE OF REF TO Icl_airplane. * Creating the list of references CREATE OBJECT cargo_plane. APPEND cargo_plane to plane_list. CREATE OBJECT passenger_plane APPEND passenger_plane to plane list. * Generic method for calucalting required fuel METHOD calculate required_fuel. DATA: plane TYPE REF TO Icl_airplane. LOOP AT plane_list INTO plane. re_fuel = re_fuel + plane->estimate_fuel_consumption( distance ). ENDLOOP. ENDMETHOD. Working example: This example assumes that the classes Icl_airplane, Icl_passnger_airplane and Icl_cargo plane (Se Subcallsing) exists. Create objects of type Icl_cargo_plane and Icl_passenger_airplane, adds them to a list in Icl_carrier, and displays the list. *8&-- **& Include ZBC404_HF_LCL_CARRIER * WGeeatena new slight Aaportiag CIASS icl_oezrier D@LEMENTATION Tac histese fllghte-saros © dolesdbe se tte * + CLASS lel_carrier DEFINITION * *— - * CLASS 1cl_carrier DEFINITION. PUBLIC SECTION. TYPES: BEGIN OF flight_list_type, connid TYPE sflight-connid, fldate TYPE sflight-fldate, airplane TYPE RAF TO icl_airplane, seatsoce TYPE sflight-seatsocc, cargo(S) TYPE p DECIMALS 3, END OF flight list type. METHODS: constructor IMPORTING im name TYPE string, get_name RETURNING value (ex_name) TYP3 string, add_a_new airplane IMPORTING im airplane TYPE REF TO 1el_airplane, create_a_new_flight importing im_connid type sflight-connid im fldate type sflight-fldate im airplane type ref to Icl_sirplane im seatsoce type sflight-seatsoce optional im cargo type p optional, display airplanes. PRIVATE SECTION. DATA: name TYPE string, list_of_airplanes TYPE TABLE OF REF TO lc. TABLE OF flight list type. ENDCLASS. -* * CLASS lel_carrier IMPLEMENTATION *~ * CLASS airplane, list_of_flights TY?= Lel_carrier IMPLEMENTATION. METHOD constructor. name = im_name. ENDMETHOD, METHOD get_name. ex_name = name. ENDMETHOD. METHOD create_a new flight. DATA: wa_list_of_flights TYPE flight_list_type. wa_list_of_flights-connid = im_connid. wa_list_of_flights-fldate ~ im fidate. wa list_of flights-airplane = im airplane. IF im seatsoce IS INITIAL. wa_list_of_flights-cargo = im_cargo. SLSE. wa_list_of flights-seatsoce = im seatsocc. ENDIF, APPEND wa_list_of flights TO list_of_flights. ENDMETHOD. MeTOD ead_a_rewaize. WOOF AT listofairplanes INTO pect he TWPE REF TO Leincergepl 0 ietearaolel METHOD add_a_new airplane. APPEND im_aizplane TO list_of_airplanes. ENDYETHOD. METHOD display_airplanes. DATA: 1_airplane TYPE REF TO Icl_aizplane. LOOP AT list_of_airplanes INTO i_aizplane. CALL METHOD 1_airplane->display_attributes. ENDLOOP. ENDMETHOD. ENDCLASS. REPORT zhed04 Af main . shatausteanatensanestenanacenanuasstanadarstanassianadanagenasenee © This reprort uses class ICL_ATRPLNAE and subclasses * LCL_CARGO_PLANE and LCL_PASSENGER AIRPLANE and class LCL CARRIER IC HU enon nin nas tannin aa niabenereieiiiabenits + super class for airplanes INCLUDE zbc404_hf_lcl_airplane. * Sub classes for aizplanes INCLUDE zbe404_hf_1cl_passenger_plane. INCLUDE 2be404 hf lel _cargo plane, * Carrie: class INCLUDE 2be404 hf lel carrier. DATA: * Type ref to classes o_passenger_aizplane TYPE REF TO lel_passenger_aizplane, c_passenger_airplane? TYPE REF TO lcl_passenger_airplane, o_cargo_plane TYPE REF TO Icl_cargo plane, o_cargo_plane? TYPE REF TO 1cl_cargo_plane, o_carrier TYPE REF TO lcl_carrier. SIART-OF-SELECTION. * Create objects CREATE OBJECT o_passenger_airplane EXPORTING im_name = 'LH505' im planetype = ‘Boing 747' im n_o_seats = 390, CREATE OBJECT 0_passenger_airplane2 EXPORTING im_name = 'SK333' im planetype - 'MDEO' im no seats = 110. CREATE OBVECY, o_sargo_plane EXPORTING im_name = 'AR13' im planetype = 'DC 3" im cargomax = 35, CREATE OBJECT ¢_cargo_plane2 EXPORTING im_name = ‘AFL124" im planetype = 'I1jutsin 2" im cargomax = 35000. CREATE OBJECT o_carsier EXPORTING im_name - 'Spritisch Airways’. Planatype: Boing 747 No. seats; 350 Name: SK333 Planetype: MD80 No.seaie: 110 Name: AR13 Planetype: DG 3 Cargo max: 36,0000 Name: AFL124 Planetype: Iliutsin 2 Cargomax: —_35.000,0000 Events Below is a simple example of how to implement an event * Add passenger and cargo planes to the list of airplanes CALL Mar D o_carrier->add_a_new_ai EXPORTING im airplane = © passenger airplane. CALL METHOD o_carrier- >add_a_new_airplane EXPORTING im airplane = op ane2. CALL METHOD © cari ssenger_air id_a_new_airplane EXPORTING im_airplane = 0 cargo plane. CALL METHOD o_cazrier->add_a new airplane EXPORTING im_airplane = ¢_cargo_plane2. * Display list of airplanes call method o_carrier->display_airplanes. Result: Name: LH505 Planetype: Boing 747 No. seats: 350 Name: SK333 Planetype: MD80 No. seats: 110 Name: AR13 Planetype: DC 3 Cargo max: 35,0000 Name: AFL124 Planetype: Iljutsin 2 Cargo max: 35.000,0000 Events Below is a simple example of how to implement an event. REPORT zbc404_hf events 5. *-~ + CLASS Icl dog DSFINITION * + CLASS Lel_dog DEFINITION. PUBLIC SECTION. * Declare events s_hungry XPORTING value (ex_time since last_meal) TYPE i, METHODS construct IMPORTING im_name TYPE string, set_time_since_last_meal MPORTING im time TYPE i, on_dog_is hungry FOR RVENT dog is hungry OF IMPORTING ex_time_since_last_meal. EW TMPLEMENTATTON * * CLASS METHOD constructor WRITE: / 'I am a dog and my name is’, im name. ENDMBTHOD. METHOD sel_time since last_meal im_time <4. Result om a dogand my name is Beefeater You fecl, | an not hungry yet You son of a biteh. | have net eaten far more than § houre Give me something to eat NOW! 1.Simple ol Thic example shows how to create a simple employes class. The constructor method is used (0 inllallze number and name of tie employee when the object is created. A display_emplayee method can be called to show the attributes of the employee, and GLASS-METHOD cosplay_no_ol_employees can be called to SKIP 1. WRITE: / 'You fool, I am not hungry yet". ELSE. * Subsrcribe for event: * set handler * FOR !0R ALL ANCES (ACTIVATION SET HANDLER on_dog is hungry FOR ALL INSTANCES ACTIVATION 'X', * Raise event RAL Bd hungry EXPORTING ex_time_since_last_meal - im_time. ENDIF. ENDMETHOD. 0 on_dog_is hungry. * Event method, called when the event dog_is hungry is raised SKIP 1, WRITE: / "You son of a bitch. I have not eaten for more than’, ex_time_since last_meal, ' NowW!*, ENDMETHOD. ENDCLASS. * * +R hours’. WRITE: / 'Give me some! poate OF-SELECTION. CREATE 08. o_dogl EXPORTING im name = 'Beefeater'. CALL METHOD © dogl- >set_time_since_last_nea EXPORTING im time = 2. * This method call will raise the event s_hungy * because time > 3 CALL METHOD 0 dogl->set_time since Last meal EXPORTING im time = 5. Result: Jam a dog and my name is Beefeater You fool, | am not hungry yet You son of a bitch. | have not eaten for more than 5 hours Give me something to eat Now! 4. Simple class This example shows how to create a simple employee class. The constructor method is used to initialize number and name of thje employee when the object is created. A display_employee method can be called to show the attributes of the employee, and CLASS-METHOD dosplay_no_of_employees can be called to show the total number of employees (Number of instances of the employee: lass) show the total number of employees (Number of instances of the employee class). REPORT zbe404_hf_events_1. ARAN eA een A TeRaH SAHA TA RAW RAMS AA USAR M NSA a RAS eREM RAMSAR EL OL EMPLOYEE LCL Employee - Definition CLASS 1cl_employee DEFINITION. PUBLIC SECTION. * = * The public section is accesible from outside *~ TYPES: BEGIN OF t employee, no TYPE i, name TYPE string, END OF t employee. METHODS: constructor IMPORTING im_employee_no TYPE i im_employee_name TYPE string, display employee. * Class methods are global for all instances CLASS-METHODS: display_no_of_employees, PROTECTED SECTION. * - * The protecetd section is accesible from the class and its subclasses * * Class data are global for all instances CLASS-DATA: g_no_of employees TYPE i. PRIVATE SECTION. * The private section is only accesible from within the classs *~ DATA: g_employee TYPE t_employee. ENDCLASS. * Implementation CLASS 1cl_employce IMPLEMENTATION. LCL Employee — METHOD constructor. g_employee-no = im employee_no. g employee-name = im employee_name. g_no_of_employees = ¢_no_of_employees + 1. ENDMETHOD, METHOD display_employee. WRITE:/ ‘Employee', ¢_employee-no, g_employee-name. ENDMETHOD. METHOD display_no_of_employees. ru / ‘Number of employees is:', g_no_of employees. ENDMETHOD. ENDCLASS. stavsteuenstensdenstenanateranenesuansantsdavatswenstenstenstenanaatees #4 R BPRORT Thie example uses a eupereiacs Jol_company_employees and two subolaeses Je bluecofar_employee and Iol_whitecollar_empioyee to add employees to alist and then dlsplay a fst of employees and there wages. The wages are caleukated in the method add_employee, butas the wages are calculated differently for blue collarempbyees and white cellar emplyees, the superclass method ladd_employce ie redellined in the subclasses Prineioles Create super class LCL_CompanyEmployees The ctass has the methods: + Constructor + Add_Employee - Acds a new employee to the list of employees + Display_Employze_List - Dispinys all employees ard there wage ‘+ Display_no_of employees - Displays total number of employees Note the use of CLASS-DATA to keep the list oi employees and number of ‘employees the same from instance fo instance. Create subclasses Iol_bluecollar_employes and Iol_whitecollar_employee. The calsses are identical, except for the recifintion of the add_employee method, Where the caciculaton of wage is diferent. Metrodes + Construstar. The construstor ie used to initialize the attributes of the employee, Note tha! the constuntor in the supclarss has to be called from within the constructor of the aubolas ERE ERECePECerereeerecereceTivecttreseree iret trecerecerererereee treaty Tt g_employeel TYPE REF TO lel employee, g employee? TYPE REF TO lel_employee. -ART-O} BCTION. CREATE OBJECT g employee EXPORTING im_employee_no = 1 m_employes name = ‘John Jones', CREATE OBJECT g employee? EXPORTING im employee no = 2 m_employee_name = ‘Sally Sumne: yee. CALL METHOD g_employee2->display_emp: >display_no_of employees CALL METHOD ¢_enployeel— @. CALL >display_enp: g_employe 2. Inheritance and polymorphism This example uses a superclass Icl_company_employees and two subclasses Ic|_bluecollar_employee and Icl_whitecollar_employee to add employees to a list and then display a list of employees and there wages. The wages are calcukated in the method add_employee, but as the wages are calculated differently for blue collar employees and white collar emplyees, the superclass method add_employee is redeifined in the subclasses. Principles: Create super class LCL_CompanyEmployees. The class has the methods: * Constructor + Add_Employee - Adds a new employee to the list of employees + Display_Employee_List - Displays all employees and there wage + Display_no_of_employees - Displays total number of employees Note the use of CLASS-DATA to keep the list of employees and number of employees the same from instance to instance. Create subclasses Icl_bluecollar_employee and Icl_whitecollar_employee. The calsses are identical, except for the redifinition of the add_employee method, where the caclculation of wage is different. Methodes: + Constructor. The constructor is used to initialize the attributes of the employee. Note that the constructor in the supclasss has to be called from within the constructor of the subclass. ‘+ Add_Employee. This is @ rediniton of the same method in the superclass. Inthe redefined clace the wage is caleuated, and the superclass metnod is called to add the employees to the emploee list. GIASS Jck_oompeny enployees DEFINITION + Add_Employee. This is a redinition of the same method in the superclass. In the redefined class the wage is calcuated, and the superclass method is called to add the employees to the emploee list.: The program REPORT 2ho404_nf events in Una naraaiiiiaeianeisaaasiasanened © Super class LCL_CompanyEnployees *+1t#++ttstenadetetstsnsrenenstaneraenseentnadeneene CLASS 1cl_company_employees DEFINITION. PUBLIC SECTION nypES: BEGIN OF t_enployee, no TYPE i, name TYPE string, wage TY! END OF t_omployee. METHODS: constructor, add_employee IMPORTING im_no TYPE £ im_name TYPE string im_wage TYPE i, display_employee_list, display no of employees. PRIVATE SECTION. CLASS-DATA: i employee list TYPE TABLE OF t employee, no_of_employees TYPE i. ENDCLASS. *-- CLASS LCL_CompanyEmployees IMPLEMENTATION CLASS 1cl_company employees IMPLEMENTATION METHOD constructor. no_of_employses = no_of_employees + 1. ENDMETKOD. METHOD add_employee. * Adds 2 new employee to the list of employees DATA: 1_employee TYPE t_employee. 1_employee-no = im_nc. 1_employee-name = im_name. 1_employee-wage = im_wage. APPEND 1_employse TO i_employee_list. ENDMEBTHOD. METHOD display employee list. * Displays all employees and there wage DATA: 1 employee TYPE L_employee. WRITE: / ‘List ef Employees". LOOP AT i_employee_list INTO 1_employee. WRITE: / 1 employee-ne, 1_employee-name, 1 employee-wage. ENDLOOP. ENDMETEOD. METHOD display_no_of_employees (CLASS Lcl_plvecol Ler employee DEFINITION anpleyse DEYIMITIO8 * Displays total number of employees SKIP 3, WRITE: / ‘Total number of employees: ENDCLASS. + 7o_of_employees. ENDMETHOD. shaeseeteteretsnaereneneeeseseestestsnersesesestensoer © gub class LCL_BlueCollaz_ Employee 1cl_pluecollar_enployee DEFINITION INHERITING FROM Iel_company_employees, PUBLIC SECTION. MetHoDS: constructor IMPORTING im no TYPE i im_name TYPE string im_hours TYPE i im_hourly_payment TYPE i, add_employee REDEFINITION. PRIVATE SECTION. DATA:no TYPE i, name TYPE string, hours TYPE i, hourly payment TYPE i. ENDCLASS. *~ CLASS LCL_BlueCollar_Employee IMPLEMENTATION CLASS Iel_bluecollar_employee IMPLEMENTATION. METHOD constructor. * The superclass constructor method must be called from the subclass * constructor methed CALL METHOD super->constructor. no = im_no. name = im-name. hours = im hours. hourly payment - im hourly payment. ENDMETHOD. METHOD add_employee. * Calculate wage an call the superclass method add_employee to add * the employee to the employee list DATA: 1 wage TYPE i, 1 wage = hoi >add_employee * hourly payment. CALL METHOD super- EXPORTING im_no = ne im_name = name im_wage - 1_wage. ENDMSTHOD. ENDCLASS. Perspapereneereversencernveraverereverteterrerttessterar art ieee’ Lch_WhiteCollar_Employee icl_whitecollar employee DEFINITION INHERITING FROM Iel_company_employees, PUBLIC SECTION. merHoDs: constructor IMPORTING im_no TYPE i vpleyes OS RANDLITOH NOE NEF TO Lelbh im_name TYPE string im monthly salary TYE i im monthly deductions TYPE i, ‘add_employee REDEFINITION. PRIVATE SECTION. DATA: no TYPE i, name TYPE string, monthly salary TYPE i, monthly deductions TYPE i. ENDCLASS. *---- CLASS LCL_WhiteCollar_Smployee IMPLEMENTATION CLASS lel_whitecollar_ employee IMPLEMENTATION. METHOD constructor. * The superclass constructor method must be called from the subclass * constructor method CALL METHOD super->constructor. no = im_no. name = im_name. monthly salary im_monthly_salary. monthly _deductions = im_monthly_deductions. ENDMETHOD. METHOD add_employee. * Calculate wage an cal the superclass method add_employee to add * the employee to the employee list DATA: 1_wage TYPE i. 1 wage = monthly salary ~ monthly deductions. CALL METHOD super->add_employee EXPORTING im_no = no im _name = name im wage = 1 wage. ENDMETHOD. ENDCLASS. seaestenetsrersderseaustteenadestetetsesesnenstsersret # RE PORT CUO HCO SOU D SUEUR Uno noe DATA: # Object references o_pluecollar_employeel TYPE REF 70 lcl_bluecollar_employee, eo whitecollar employee! TYPE REY YO 1cl_whitecollar employee. SYARI-OF- SELECTION. * Create bluecollar employee obeject CREATE OBJECT o_bluecollar_employeel EXPORTING im_no = 1 im name = 'Gylle Kazen' im hours - 38 im hourly payment = 75. * Add bluecollar employee to employee list CALL MBTHOD © bluecollar_employee!->add_enpioyee EXPORTING im_no = 1 im name = 'Gylle Karen‘ im wage = 0. * Create whitecollar employee obeject CREATE OBJECT o_whitecollar_employeel EXPORTING im_na = 2 im_name = ‘John Dickens’ im monthly salary = 10000 The resuiting report Listoi Employees 1 Karen dohnson 2.350 2 den Dickens 7.500 Total number of employees: 2 a. Interfaces This example is similiar to th eprevious example, however an interface ie impemented with the method add_employes. Noie that the interface is only implomonted in tho cuporolase (Tho INTERFACE ctament), but aleo used in tho subelasses. The interiace in the example only contains 2 method, but an iteface can also contain attrbutas, constants, typos and alias names. The output from example 2 ie similiar to the output in example 2, All changes in the pragram compared t2 example 2.are marked with red im monthly deductions = 2500. * Add biuecollar enployee to employee list CALL Mar D o_whitecollar_enployee1->add_employee EXPORTING im no = 1 im_name = ‘Karen Johnson" im wage = 0. * Display employee list and numb employees. Note that the result * will be the same when called fron o_whitecollar_employee are defined * as st * 0 blueco METHODS! collar_employcel, because the methods i CALL METHOD o_whitecollar employee! v, isplay_employee_list. CALL METHOD o_whitecollar |_no_of_employees. The resulting report List of Employees 1 Karen Johnson 2.850 2 John Dickens 7.500 Total number of employees: 2 3. Interfaces This example is similiar to th eprevious example, however an interface is implemented with the method add_employee. Note that the interface is only implemented in the superclass ( The INTERFACE stament), but also used in the subclasses. The interface in the example only contains a method, but an iterface can also contain attrbutes, constants, types and alias names. The output from example 3 is similiar to the output in example 2. All changes in the program compared to example 2 are marked with red. REPORT zbea04_hf events 3. * © INTERF 2 - if_employee METHODS add_employee IMPORTING im_no TYPE £ im_name TYPE s' image TY . DONOR eaaweaenaeianeaaueeeened « Super class zeh Res HEHE EELS ORES JUAN BIBS U IE aninii ie panyEnp: employees DEFINITION (CIASS icl_bivecolier_enployee DEFTHITION PUBLIC SECTION. INTERFACES 1if_employee. TYPR: BEGIN OF + employee, no TYPE i, name TYPE string, wage TYPS i, END OF t employee. METHODS: constructor, * add_employee "Removed IMPORTING im no TYPE i im_name TYPE string im wage TYPE i, display employee list, display_no_of_employees. PRIVATE SECTION. CLASS-DATA: i_employee_list TYPE TABLE OF t_employee, no_of_employees TYPE i. ENDCLASS. *-- CLASS LCL_CompanyEmployees IMPLEMENTATION CLASS 1cl_company_employees IMPLEMENTATION . METHOD constructor. no_of_employees = no_ef_employees + 1. ENDMETKOD. METHOD Lif_employee~add_employee. * Adds a new employee to the list of employees DATA: 1_employee TYPE t_employee. 1_employee-no = im_nc. 1_employee-name = im_name. 1_employee-wage = im_wage. APPEND 1_employse TO i_employee_list. ENDMETEOD. METHOD display employee list. * Displays all employees and there wage DATA: 1 employee TYPE t_employee. WRITE: / ‘List of Employees’. LOOP AT i_employee_list INTO 1_employee. WRITE: / 1 employee-no, 1 employee-name, + employee-wage. ENDLOOP. ENDMETEOD. METHOD display ne of employees. * Displays total number of employees SKIP 3. WRITE: / ‘Total number of employees:', no_of employees. BNDMETHOD. ENDCLASS. UNRUH Un eineanaeeener & Sub class LCh_BlueCollar_Employee BesdaaStAWRESER RAO EAHEEREESAEAEEREAURESEREAEEERHENSEAY CLASS. 1cl_bluecollar_ employee DEFINITION INHERITING FROM lcl_company_employees. PUBLIC SECTION. METHODS: constructor CIASS ict_pluecsiier erp) ethsd addenplayee to add CLASS ict_wnstecolias employee DEYIMITIOS IMPORTING im_no TYPE i im_name TYPE string im_hours TYPE i im hourly payment TYPE i, Lif employee~add_employee REDEFINITION.. PRIVATE SECTION. DATA:no TYPE i, name TYPE string, hours TYPE i, hous payment TYPE i. ENDCLASS. *—~ CLASS LCL_BlueCollar_Employee IMPLEMENTATION CLASS {cl_bluecollar_employee IMPLEMENTATION. METHOD constructor. * The superclass constructor method must be called from the subclass * constructor method CALL METHOD super->constructor. no = im_no. name = im name. hours = im hours. hourly payment = im hourly payment. ENDMETHOD. METHOD Lif_employee~add_employee. * Calculate wage an call the superclass method add_employee to add * the employee to the employee list DATA: l_wage TYPE i. 1_wage = hour: >1if_employee~add_employee * hourly_payment. CALL METHOD super- EXPORTING im_no = no im_name = name im_wage ~ 1_wage. ENDMSTHOD. ENDCLASS. shadanatedansdenadananseansennaadatetenatanatanattienad # Sub class ICh_WhiteCollar_Employse icl_whitecollar employee DEFINITION INHERITING FROM Iel_company_employees. PUBLIC SECTION. METHODS: constructor IMPORTING im_no TYPE 4 im name TYPE string im monthly salary T¥2E 4 im monthly deductions TYPZ i, Lif_employee~add_employee REDEFINITION. PRIVATE SECTION. pata: no TYPE i, name TYPE string, monthly_salary TYPE i, monthly_deductions TYPE i. ENDCLASS. *---- CLASS LCL_WhiteCollar_Employee IMPLEMENTATION CLASS lel_whitecollar employee IMPLEMENTATION METHOD constructor. teLbiuscet ecblancol ae nup leven CREATE CBIRCE a_ehitecotlar_enplayee! fie (LASS-HETODS) * The superclass constructor method must be called from the subclass * constructor method CALL METHOD super->constructor. no = im_no. name = im_name, monthly salary = im_monthly salary. monthly deductions = im monthly deductions. ENDMETHOD. METHOD 1if_employee~add_employee. * Calculate wage an call the superclass method add_employee to add * the employee to the employee List DATA: 1_wage TYPE i, 1_wage = monthly salary ~ monthly deductions. CALL METHOD Super->lif_employee~add_employee EXPORTING im_no = ne im_mame = name im_wage = l_wage. ENDMSTHOD. ENDCLASS. ORR RARER RE BORD Ii Unni ianiaiiirietiaatacenstaaauananeted DATA: * Object references © bluecollar employeel TYPE REF 70 lel bluecollar employee, o_whitecollar_employeel TYPE REF TO lcl_whitecollar_employee. START-OF- SELECTION. * Create bluecollar employee obeject CREATE OBJECT © bluecollar_employee! EXPORTING im_no = 1 im_name = ‘Gylle Karen’ im_hours = 38 im_hourly payment = 75, * Add bluecollar employee to employee list CALL METHOD 0_bluecollar_employee!->1if_employee~add_employee EXPORTING im_no = 1 im_name = ‘Karen Johnson’ im_wage = 0. * Create whitecollar employee cbeject CREATE OBJECT o_whitecollar_enployeel EXPORTING im_no = 2 im_name = "John Dickens’ im monthly salary = 10000 im monthly deductions 2500. * Add bluecollar employee to employee List CALL METHOD 0_whitecollar_employeel->lif_employee~add_employee EXPORTING im_no = 1 im_name = 'Gylle Karen! im wage = 0. * Display employee list and number of employees. Note that the result * will be the same when called from o.whitecollar employee! or * © bluecolarcoliar_employeel, because the methods are defined * as static (CLASS-METHODS) CALL METHOD 0_whitecollar_employeel->display_employee_list. CALL METHOD o_whitecollar_employeel->display_no_of employees. Events This is the same example as example 4. Allchanges are marked with red. There have been no cargec to the eubolassos, only to the euperclaes and tho roport, op the code for th esubclasses is not shown. Fora simple example refer to Events in Examoles (CLASS JeL_conpany_enployeet IMPLEMENTATION. 4. Events This is the same example as example 4. All changes are marked with red. There have been no canges to the subclasses, only to the superclass and the report, sp the code for th esubclasses is not shown. For a simple example refer to Events in Examples REPORT zbe404_hf_events4. * -* * INTERFACE 1if employee *~ * INTERFACE 1if_employee METHODS: add_employee IMPORTING im_no TYPE £ im_name TYPE string im_wage TYPE i. ENDINTERFACE. HOO Onno onieaneener © super class LCL _CompanyEnployees ++ SHS AReRetaRaRanaeaeaeae CLASS 1cl_company employees DEFINITION. PUBLIC SECTION. TYPES: BEGIN OF t_employee, no TYPE i, name TYPE string, wage TYPS i, END OF t_employee. * Declare event. Note that declaration could also be placed in the * interface EVENTS: employee_added_to_list EXPORTING value (ex_employee_name) TYPE string. * CLAS also be defined as class-events Events can INTERFACES 1if_employee. METHODS: constructor, display employee list, display no of employees, * Declare event method on_employee_acided_to_1i FOR EVENT employee _added_to_list oF lcl_company employees IMPORTING ex_enployes_name sender, PRIVATE SECTION. CLASS-DATA: i_employee list TYPE TABLE OF employee, no_of_employees TYPE i. SNDCLASS. CLASS LCL_CompanyEmployees IMPLEMENTATION CLASS lel_company_enployees IMPLEMENTATION. MeHop constructor. see code in example 3... CEASE Sol_blveoetion enplegee DMPLIEWEREZOH, See code in example 3... CIASS Jcl_waitecollarempleyee See code in example 3... (CIES Iel_whiteco! tasampleyes IMDLEMENTATTOH. See code in example 3... ne_of_employees ~ no_of employees + 1. ENDMETHOD. METHOD Lif _employee~add employee. * Adds a new employee to the list of employees DATA: 1_employee TYPE t_employee. 1_employee-no = im_no. 1_employee-name = im_name. 1_employee-wage im wage. APPEND 2 employee TO i employee_list. * Raise event employee_added_to list RAISS EVENT employee_added_to_list EXPORTING ex_employee_name = 1_employee-name. ENDMBTHOD. METHOD display employee list, * Displays all employees and there wage DATA: l_employee TYPE t_employee. WRITE: / "List of Employees". LOOP AT ivemployee_list INTO 1 employee. WRITE: / 1_employee-no, 1_employee-name, 2_employee-wage. ENDLOOP ENDMETHOD. METHOD display_no_of_employees. * Displays total number of employees SKIP 3. WRITE: / ‘Total number of employees:', no_of METHOD on_employee_added_to list. * Event method mployees. ENDMETHOD. WRITE: / ‘Employee added to list", ex_employee_name. ENDMETHOD. ENDCLASS SSE UE ERE In eSO EE IOneEEnnninremnermntet * Bub Glass LCL_BlueCollaz_Enployee shadabansuanatinanaanebanasenaneasstenadaneneneneeened CLASS 1cl_pluecollar_employee DEFINITION INHERITING FROM [el_company_employces. See code in example 3... ENDCLASS, CLASS, {cl_bluecollar_employee IMPLEMENTATION. See code in example 3... SNDCLASS. OOOO Onno OOo & Sub class LCL WhiteCollar Employee seadetenensteraderesauentesnaaresavesstenederesensteeet CLASS lcl_whitecollar_employee DEFINITION See code in example ENDCLASS. CLASS lel_whitecollar_employee IMPLEMENTATION. See code in example 3... ENDCLASS. shavstenetatenadansssushatenadeeesietedeeetenstanenster # RE PORT narra inn nnoooninnnnieninnnniiioniinnnneeninrensid DATA: * Object references Result Employee added to lst Karen Johnson Employee added to lst John Dickens Listoi Employoes 1 Karen Johnson 2.350 2 John Dickens 7500 Total number of employees: 2 o_bluecollar_employeel TYPE REF 10 lel_bluecollar_employee, © whitecollar employeel TYPE REF 70 lel whitecollar employee. START-OF- SELECTION. * Create bluecollar employee obeject CREATE OBJECT o bluecollar employee! EXPORTING im_no = 1 im_name = ‘Karen Johnson‘ im_hours = 38 in_hourly payment = 75. * Register event for o_bluecollar_employeel SET EANDLER o_bluecollar_employee!->on_employee_added_to list FOR o bluecollar_employeel. * Add bluecollar employee to employee list CALL METHOD 0_bluecollar_employee!->1if_enployee~add_employee EXPORTING im_no = 1 im_name = ‘Gylle Karen' imwage = 0. * Create whitecollar employee obeject CREATE OBJECT o whitecollar enployeel EXPORTING im_no = 2 Sm_name = ‘John Dickens! im monthly salary = 10000 im monthly deductions 2500. * Register event for o_shitecollar_employeel SET HANDLER o_whitecollar_employeel->on_enployee_added to list FOR o_whitecollar_employeel. + Add bluecollar employee to employee List CALL METHOD o_whitecollar_employee1->lif_employee~add_enployee EXPORTING im_no = 1 im_name = 'Gylle Karen' im wage = 0. * Display employee list and number of employees. Note that the result * will be the same when called from o_whitecollar_employeel or * o bluecolarcollar_employeel, because the methods are defined * as static (CLASS-METHODS) CALL METHOD o_whitecollar_employee!->display_employee_list. CALL METHOD o_whitecollar_employeel->display_no_of_employees. Result: Employee added to list Karen Johnson Employee added to list John Dickens List of Employees 1 Karen Johnson 2.850 2 John Dickens 7.500 Total number of employee: General The contro framework consists of 2 parts + CL_GUL_CFW contains methods that provide services for communicaton with the Frontend, and can be used beth by contol wiper celeses and by control progtrammers + The CL_GUI_OBJECT encapeulates ActiveX or JavaBeans methods, while CL_GUI_CONTROL is responsibie for displaying the control on the CL_GUL_OBJECT = CL_GUI_CONTROL-> CL_GUI_* (Wrapper olaze) Thoee classes containe methods that are enherited ky eubesquent clazeos® in the enheritance tree. Synchronization Flush FG calls s used to synchronize the front and backend. This synchronization takee pake at ome predifined pointe in the program flow. However you should not rely entitely on automatic synchronization, but force synchronization with the Flush mathod when necessary Bear in mind that the synehronization/RFC calls represeamts a botilenack £0 you should keep the not use the Flush method to minimum Syntax (CALL METHOD cl_gui_efw=>FLUSH Set up event handling for controls There are two types of events: Application events, T The flow logis of the screen is processed after the event (The PAI module is, processed) Inthe events table the event must be registred as an application event by seting then Feld epplevent to x’ Control Framework and enheritance hierarchy The control framework consists of 2 parts: + CL_GUI_CFW contains methods that provide services for communication with the frontend, and can be used both by control wrapper calsses and by control progtrammers + The CL_GUI_OBJECT encapsulates ActiveX or JavaBeans methods, while CL_GUI_CONTROL is responsible for displaying the control on the screen CL_GUI_OBJECT -> CL_GUI_CONTROL -> CL_GUI_* (Wrapper class) These classes contains methods that are enherited by subsequent classes in the enheritance tree. Synchronization/Flush RFC calls is used to synchronize the front and backend, This synchronization takes palce at some predifined points in the program flow. However you should not rely entirely on automatic synchronization, but force synchronization with the Flush method when necessary. Bear in mind that the synchronization/RFC calls represenmts a bottleneck, so you should keep the not use the Flush method to a minimum. ‘Syntax: CALL METHOD cl_gui_cfw=>FLUSH Set up event handling for controls. There are two types of events: Application events. T The flow logic of the screen is processed after the event (The PAI module is processed). In the events table the event must be registred as an application event by setting then field appl_event to 'X': wa evenis-eventid = cl qui texiedi=sevent double click wa_evenis-appl_event = °K ‘append wa_evenis to events Important: The dispatch method of cL gui_cfw must be called in the PAI module: CALL METHOD cl gui ctw=sdispatch, System events For system events the jlow-logic of the screen is not executed. That means that the PAland PBO modules are rot processed. Inthe evente table the the field applevent must be soi to SAPCE: wa_evente-oventid wa_events-appl_event append we_events to i ¢ gui textodi-revent_double_olick. The dispatch methed of el_gui_efw must NOT be called. Example Its presumed that a SAP toolbar contra named go_toolbaroi class cL gui_toobarhas been delined. To sez aconplete exampke of how to handle events, referta The SAP toalhar control Data: +1. Define and instance of the eventhandler class. the event handler elaes is defined aiter the data dacalaration the class must be declared as DEFERRED in the top of the program CLASS cls_event_handler DEFINITION DEFERRED. ‘go_event handler TYPE AEF TO cls_event_handler, +2. Dafine table for registration of events, Nowe thata TYPE REF to cls_event handler must be created before you reference types cnll_simple_events and ent_simpl_event gievents TYPE catl_sinple_events, * Worepace for table glevents event TYPE cnt_simple_evert. +3. Define and implement eventhandler class CLASS cls_event_handler DEFINITION, PUBLIC SECTION, METHODS: Syntax wa_events-eventid = cl_gui_textedit=>event_double_click. wa_events-appl_even' append wa_events to i_events Important: The dispatch method of cl_gui_cfw must be called in the PAI module: CALL METHOD cl_gui_cfw=>dispatch. System events. For system events the flow-logic of the screen is not executed. That means that the PAI and PBO modules are not processed. In the events table the the field appl_event must be set to SAPCE: wa_events-eventid = cl_gui_textedit=>event_double_click. wa_events-appl_event = space. append wa_events to i_events, The dispatch method of cl_gui_cfw must NOT be called. Example Itis presumed that a SAP toolbar control named go_toolbar of class cl_gui_toolbar has been defined. To see a complete example of how to handle events, refer to The SAP toolbar control. Data: * 1. Define and instance of the eventhandler class. * If the event handler class is defined after the data decalaration * the class must be declared as DEFERRED in the top of the program: CLASS cls_event_handler DEFINITION DEFERRED. go_event_handler TYPE REF TO cls_event_handler, * 2. Define table for registration of events. * Note that a TYPE REF to cls_event_handler must be created before you an * reference types cntl_simple_events and cntl_simple_event gi_events TYPE entl_simple_events, * Workspace for table gi_events g_event TYPE cntl_simple_event. * 3, Define and implement eventhandler class CLASS cls_event_handler DEFINITION. PUBLIC SECTION. METHODS: * Syntax: method name> FOR EVENT OF m_d_function_selected, GLeventapplevent =X! ‘This is an application event APPEND ¢ event TO gi events. append more events Inecestary “5. Use the events table to register events for the control CALL METHOD go_toolharsset registered events, EXPORTING events = gLevents, +6. Create event handler CREATE OBJECT go_event handler "syntax * SET HANDLER + FOR on function_selcted FOR go_toolbar .d OF ol gui toolbar clare a reference. Scenario: DATA: 2_my_elace TYPE REF TO lol_myclae: CLASS leL_myslase. ENDGLASS. * FOR EVENT * OF on_function_selected FOR EVENT function_selected OF ol_gui_toolbar IMPORTING fcode, ENDCLASS. CLASS cls_event_handler IMPLEMENTATION METHOD on_function_selected. * Do something when the event is raised ENDMETHOD. ENDCLASS. * 4. Append events to the events table * The Event Id can be found in the control documentation. Note that The event below is registred as an application event g_event-eventid = go_toolbar->m_id_function_selected. g_event-appl_event = 'X’. "This is an application event APPEND g_event TO gi_events. .... append more events i necessary... * 5. Use the events table to register events for the control CALL METHOD go_toolbar->set_registered_events EXPORTING events = gi_events. * 6, Create event handler CREATE OBJECT go_event_handler, * Syntax: * SET HANDLER -> * FOR SET HANDLER go_event_handler->on_function_selected FOR go_toolbar. Declare a reference variable before the class has been defined Scenario: DATA: o_my_class TYPE REF TO Icl_myclass. CLASS Icl_myclass..... ENDCLASS This will cause an error because the definition of class Icl_myolass is after the declaration. Solution: Deine the claes in the beginning of the progrom with DEFINITION DEFERRED: LASS lel_myolaes DEFINITION DEFERRED, DATA: 9_my_slass TYPE REF TO lol_myclass CLASS leL_myslass. ENDGLASS: focus to a control Set the focus to a control ramed go_gti: CALL METHOD cl gal conele>est focus EXPORTING contol = goa To Use BADI - Business Add In you need to Understand ABAP OO Interface Concept Content Author: Jayants Narayan Chowbs Author Email: sse@calvenl,ackin Author Website: bup:ia wy. gencitcs somlojne * For Rajets 00 ans BAdI Edveation This will cause an error because the definition of class Icl_myclass is after the declaration Solution: Define the class in the beginning of the program with DEFINITION DEFERRED: CLASS Icl_myclass DEFINITION DEFERRED DATA: o_my_class TYPE REF TO Icl_myclass. CLASS Icl_myciass..... ENDCLASS Set focus to a control Set the focus to a control named go_grid! CALL METHOD cl_gui_control=: EXPORTING control = go_grd To Use BADI - Business Add In you need to Understand ABAP OO Interface Concept Content Author: Jayanta Narayan Choudhuri Author Email: sss@ hutp://www.geocities.com/ojne set_focus .vsnl.net.in Author Website: * For Rajat's OO ans BAdI Education ves like a Shape" Adverb/Adjective Methods: getArea Returning Value(area) Type F, ce Returl ing e) Type F. ‘lass that behaves like a Shape Class CCircle Definit Public Section 2k Saeare Interfaces IShape. Aliases: getArea For TShape~gevArea, getCircumference For [Shape-getCizcumference. Methods: Constructor Importing pRadius Type F, setRadius Importing pRadius ype F, getRadius Returning Value (pRadius) Type F. Private Section. Data radius Type F. Constants PI Type F Value '3.141592365359". EndClass Class CCircle Implementation. Method Constructor. radius pRadius. EndMethod. Method setRadius. zadius = pRadius. Endlethod. Method getRadius. pRadius = radius. Endethod. Method Ishape~getArea. Compute area = 2 * PI * radius. EndMethod, Method Ishape~getCircumference. pre Compute circumference dius * radius. EndMethod. EnéClass. * A Square Class Class CSquare Definition. Public Section. Interfaces TShape. Aliases: getArea For TShape~g} getCircumference For IShape~ger Methods: Constructor Importing pSide Type Private Section. Data side Type F. EndClass. Class Square Implementation. Method Constructor. eet besa type Fy ono tmape-cnichscentnreaees ait + tenet side ~ pSide. EndMethed. Method Tshape~getArea. Compute area = side * side. EndMethod. Method IShape-getCircunference. Compute circumference = 4 * side. EndMethod. EndClass. + A Rectangle Class Class CRectangle Definition. Public Section. Interfaces shape. Aliases: getAcea For IShape-getArea, getCircunference For Ishape~getCizcumference. Methods: Constructor Importing pHeight Type ¥ plength Type F. Private Section. pata: height type F, length tye #. EndClass. Class CRectangle Implementation. Method Constcuctor. height = plleight. length = pLength. EndMethod. Method IShape~getArea. Compute azea ~ height * length. Endlethod. Method TShape-getCircumference. Compute cizcunference = 2 * ( height + Length ). EndMethod. BnéClass. + START of PROGRAM * Array of Shapes Dat: Behaviour OneShape Type Ref To IShape, " One Object with Shape ShapeTable Type Table Of Ref To IShape. " Array of Objects with Shape Behaviour * Concrete Objects with TShape Behaviour! Eceate Object €2 Exporting pRadius - °5,0. Create object RL meporting plleight = 12.0" puengen = "2647 Data: Cl Type Ref To Circle, Sl Type Ref To CSquare, RI Type Ref To cRectangle, C2 Type Ref To CCircle, 82 Type Ref To CSquare, R2 Type Ref To cRectangle. Data: deser_ref TYPE ref to CL_ABAP_TYPSDRSCR, ClassName Type String, Serial Type I. Data: myArea Type F, myCircumference Type START-OP-SELECTION. Create Object Cl Exporting pRadius = '2.5'. Create Object C2 Exporting pRadius = "5.0". Create Object 51 Exporting pSide = '3.5'. Create Object 52 Exporting pSide "6.0". Create Object Rl Exporting pHeight = '2.8' plength = 13.4". Create Object R2 Exporting pHeight = '1.7' plength = "6.3". * append in any order! Append S1 to ShapeTable. Append R2 to ShapeTable. Append Rl to ShapeTable. Append C2 to ShapeTable. Append Cl to ShapeTable. Append S2 to ShapeTable. Serial = 0. loop At ShapeTable into OneShape. Call Method OneShape->getarea Receiving area = myArea. Call Methed OneShape- >getCircumference Receiving circumference = myCircunference. descr_ref ~ CL_ABAP_TYPEDESCR->Describe_By_Ohject_Ref( OneShape ). Call Method deser_ref>get_relative_name Receiving P_RELATIVE NAME = ClassNane. Add 1 to Serial. Write: / Serial, ClassNane. Write: / ‘Area ', myArea Decimals 4 Exponent 0. Write: / ‘Circumference ' ) myCircunference Decimals 4 Exponent 0. Write: /. EndLoop. Example 1: Creating the TextEdit control This is a simple example of how to implementa text edit control Steps 1. Create a report 2. Inthe siart of selection event add: SET SCREEN "100" 3. Create screen 100 4. Place a custom control on the screen by choosing the custom contol icon which can be recognized by the letter Cand give it the name MYCONTAINER 1 5. Te be abb to ext the progiam, act! a pushbutton with the function code EXIT, 6. Inthe elements list enter the name OK_GODE for the element of type OK. The code ** Results * 1 CSQUARE * Area 12.2500 ¥ Circumference 14.0000 * * 2 CRECTANGLE * Area 10.7100 * Circumference 16.0000 * * 3 CRECTANGLE * Area 4 CCIRCLE * Area 31. * cizew 78.5398 Area 36 Example 1: Creating the TextEdit control This is a simple example of how to implement a text edit control. Steps 1, Create a report 2. In the start of selection event add: SET SCREEN '100’. 3. Create screen 100 4, Place a custom control on the screen by choosing the custom control icon which can be recognized by the letter 'C’, and give it the name MYCONTAINERI. 5. To be able to exit the program, add a pushbutton with the function code EXIT. 6. In the elements list enter the name OK_CODE for the element of type OK. The code REPORT sapmz_hf_controls1 . CONSTANTS: ine length TYPE i VALUE 254. DATA, ence to the custom container fe LIKE sy-ucomm. DATA: * Create m_container TYPE REF TO cl_gui_custom container, * Create reference to the TextEdit control editor TYPE REF TO cl_gui_textedit, repid LTKB sy-repid. START-OF-SELECTION. SET SCREEN '100'. * + * MODULE USER_COMMAND_0100 INPUT * + * MODULE user_conmand_0100 INPUT. CASE ok code. WHEN ‘EXIT’. LEAVE TO SCREEN 0, ENOCASE. ENDMODULE. " USER_COMMAND_0100 INPUT *a~ * *& Module STATUS_0100 OUTPUT *6- - * MODULE status_0100 OUTPUT. * The Textdit control shoul only be initialized the first time the * P30 module executes IP editor IS INITIAL. repid = sy-vepid. * Create ebejct for custom container CREATE OBJECT custom_container EXPORTING container_name = 'MYCONTAINERI" EXCEPTIONS entl_error = 1 enti system error = 2 create error ~ 3 lifetime error lifetime_dynpro_dynpro_link = 5 others = 6 . TF sy-subre <> 0. MESSAGE ID sy-msgid TYPE '1' NUMBER sy-msgno WITH sy-nsgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. * Create obejct. for the TextBditor control CREATE OBJECT editor EXPORTING wordwrap_mode = cl_gui_textedit=>wordwap at fixed position wordwzap position line_length wordwrap_to_linebreak_mode = cl_gui_textedit=>true parent = custom_container EXCEPTIONS error_entl_create = 1 error_entl_init = 2 error_entl_link = 3 error_dp_create = 4 gui_type_not_supported = § others = 6 . IF sy-subre <> 0. The result - Application event Example 2: Event hand There are 2 types of events: spective of the screen «© System events. These events are triggerede flow logic + Application events. The PAl module is processed alteran event The handling Inthis example an appication event is added to the program in example 1. New ‘code is marked with red, MESSAGE ID sy-msgid TYPE '1' NUMBER sy-msgno sy-msgvl 5: ENDIF. ENDIF. ENDMODULE. " STATUS 0100 oUF msgv2 sy-msgv3 The result Example 2: Event handling - Application event There are 2 types of events: + System events, These events are triggerede irrespective of the screen flow-logic. * Application events, The PAI module is processed after an event. The method CL_GUI_CFW=>DISPATCH must be called to initiate event handling In this example an application event is added to the program in example 1. New code is marked with red. Steps: Steps: 1. Create an inputioutput field on screen 100, where the event type can be output. Name EVENT_TYPE The code: 1. Create an input/output field on screen 100, where the event type can be output. Name it EVENT_TYPE The code: REPORT sapmz_hf_controls1 . CONSTANTS: line length TYPE i VALUE 254. DATA: ok_code LIKE sy-ucomm. DATA: * Create reference to the custom container custom_container TYPE REF TO cl_gui_custom_container, * Create reference to the Yextedit control editor TYPE REF TO cl_gui_textedit, repid LIKE sy-repid. Stietieninesnisineenmennianeatinninanisaansninenisninertenstseniest + Impmenting events seteetaneneenesausantenetenennenanansanttantaseneanesautananeetaeentes DATA: event_type(20) TYPE c, * Internal table for events that should be registred Aevents TYPE entl simple events, * Structure for oneline of the table ‘wa_events TYPE entl_simple_event, *—————————___-____________+ ¥ CLASS. IeL_event_handler DEFINITION ¥————————__-________________" cLass cl event_handler DEFINITION. PUBLIC SECTION. CLASS-METHODS: catch_dblelick FOR EVENT dblelick OF cl_gui_textedit IMPORTING sender. ENDCLASS. CLASS lel_event_handler IMPLEMENTATION. METHOD catch dblelick. event_type = ‘Event DBICLICK raised’. ENDMETHOD. ENDCLASS START-OF-SELECTION, CLEAR w: events. refresh i events. SET SCREEN '100". MODULE USER_COMMAND_0100 INPUT * * * MODULE user_command_0100 INPUT. CASE ok. WHEN ‘EXIT'. LEAVE T0 SCREEN 0, WHEN OTHE! Ged Bi veel meth bo ind tictermenliontdon epee: toeatiabe, worausoputa_linesresknose = tne erent handler nethod to the event and the + texezaie control * Call the Dispacth method to initiate application event handling call method cl_gui_cfw->Dispatch. ENDCASE, ENDMODUSE. " JSER_COMMAND_0100 INPUT *4~ - * *& Module STATUS_0100 OUTPUT *5- * MODULE status 0100 OUTPUT. * The TextEdit contro! shoul only be initialized the first time the * PBO module executes IF editer IS INITIAL. repid = sy-zepid. * Create obejct for custom container CREATE OBJECT EXPORTING container_name = 'MYCONTAINERI" EXCEPTIONS stom_container entl_error = 1 enti_system error = 2 create_error lifetime dynpro_dynpro_link = 5 others = 6 . IF ay-subre <> 0. 3 lifetime error MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. * Create obejct, for the TextBditor control CREATE OBJECT editor EXPORTING wordwrap_mode cl_gui_textedit=>wordweap at fixed position wordweap position = line_length wordwrap_to_linebreak_mode = cl_gui_textedit=>true parent custom_container EXCEPTIONS error_entl_create = 1 error_entl_init = 2 error_entl_link = 3 error_dp create = 4 gui_type_not_supported = § others = 6 . IF sy-subre > 0) MESSAGE ID sy-magid TYPE 'I' NUMBER sy msgno WITH sy-msgyl sy-msgv2 sy-msgy3 sy-msgv4. ENDIF. * Link the event handler method to the event and the * TextEdit control SEY HANDLER icl_event_handler=>catch dbiclick POR editor. * Register the event in the internal table i_events wa_events-eventid = cl_gui_textedit->event_double_click. wa_events-appl_event = 'X'. “This is an application event Result: When you double click on the TextEdit contiol, the inoutiouput field should show the toxt Event DBLOLICK Example 9: Event handling - System event Systom events are passed iire spective of the flow-logie of the screen. To impementa system event change the code from example 2 as follows: Reoult: When you double clicks on the TextEdit control nothing happens, since the flow- Logie of the soreen an cthe fielie transport is ignore. append wa_events to i_events. * Pass the table to the TextEdit control using method * ‘set_registred_events red_events exporting events = i events. ENDIF. ENDMODULE. * STATUS 0100 ovT2UT Result: When you double click on the TextEdit control, the input/oupult field should show the text: Event DBLCLICK Example 3: Event handling « System event System events are passed irrespective of the flow-logic of the screen. To implement a system event change the code from example 2 as follows: Code: CLASS 1e1_event_handler IMPLEMENTAT METHOD Reacting DBLCLICK raised’. * exporting new_code = "SHOW". MODULE use: mmand_0100 INPUT. code... ee... WHEN "SHOW", call method event_type = 'systen ick _gui_cfw=>Dispatch. ENDMODULZ. " USER COMMAND 0100 INPUT DCA MODULE status_0100 oUT2UT code ~ wa_events-app!_event = "x". "This is ai application wa_events-appl_event = s a system event ENDIF, ENDMODULE. " -ATUS_0100 OUTPUT Result: When you double clicks on the TextEdit control nothing happens, since the flow- logic of the screen an dthe fielde transport is ignore. Example 4: Calling methods of the control Inthis exercise a function that loads the texts of an internal table into the text window, is implemented. Steps: Define ancterh pushbutton on the ssteen, that activates the method that fils the TextEdit control, Give iiname PUSHBUTTON. IMPORT and function code IMP. Define a form GREATE_TEXTS that carries out the teyt import. ‘Only changes to the code in example 2 is show. Code: MODULE use1_sommend_0100 INPUT. ‘CASE ok_code, code. WHEN MP» periorm load_texts. ENDCASE ENDMODULE. Example 4: Calling methods of the control In this exercise a function that loads the texts of an internal table into the text window, is implemented Steps: Define anoterh pushbutton on the screen, that activates the method that fills the ‘TextEdit control, Give itname PUSHBUTTON_IMPORT and function code IMP. Define a form CREATE_TEXTS that carries out the text import. Only changes to the code in example 2 is show. Code: MODULE user_command_0100 INPUT. CASE ok_code. code... WHEN ‘IMP’ _COMMAN 00 INPUT ¥& + 5 Porm ad_texts *6 * * This * the t set_text_as ple with texts. The the contents of control using method * * FORM load texts ovPES BEGIN OF t_texttable, ine(Line_length) TYPE c, END OF t_texttable. DATA i_texttable TYPE TABLE OF t_texttable. * Create internal table with texts APPEND ‘This a method that fills the TextEdit control’ TO i_texttable APPEND ‘with a text.’ 10 i_texctable. Do 10 TIMES. lo world !' TO i_cexttable. ENDO. * Load TextEdit control with EXPORTING table = i texttable. IF sy-subre > 0. * Display an error message Example 5: Responding to an event When you doubé click on a text line in the TextEdit control, you want i! to be prefixed wih 2 The line number ofthe TextEdit contro that is double clicked, is retreived using method GET_SELECTION_POS, The internal text tabie is reloaded iroin the TextEdt control with method GET_TEXT_AS_RSTABLE. The position of the double click in the Text=dit control is used te find the enity in the table, and the ‘entry is preficed with "and loaded into the Tex'Edit control again, The program should be changed so thatthe internal table (texttabie is global ‘anda global flag g_loaded added, The lead of the table should be moved to the PBO module. The changes in thie code are marked with red. The whole program now look ike thie Code BXIT. ENDIF. * All methods that operates on controls are transferred to the frontend * by a REC calls. the method ELUSH is used to determine when this is CALL METH D cl_gul_cfw=>flush. IF s ubre > 0. * Display an error message NDIF. ENDFORM. " create texts Example 5: Responding to an event When you double click on a text line in the TextEdit control, you want it to be prefixed with a™. The line number of the TextEdit control that is double clicked, is retreived using method GET_SELECTION_POS. The internal text table is reloaded froim the TextEdit control with method GET_TEXT_AS_R3TABLE. The position of the double click in the TextEdit control is used to find the entry in the table, and the entry is prefixed with“ and loaded into the TextEdit contro! again. The program should be changed so that the internal table i_texttable is global, and a global fiag g_loaded added. The load of the table should be moved to the PBO module. The changes in thje code are marked with red. The whole program now looks like this: Code REPORT sapmz_hf_controls] . CONSTANTS: TYPE i VALUS 254. DATA: ok_code LIKE sy-ucomm. DATA: * Create the custom cont container TYPE REF TO cl_gui_custom_container, * Create reference 2 REF TO cl_gui_textedit, repid LIKE sy-rep: Utillity table to load texts pperesereseuane ve senvesttercrccerererecirererececetcteeeceececeaerenan cet ys BEGIN OF t_texttable, ine (1ine_length) TYPE c, END OF t_texttable. DATA: Lexttable 1 PE TABLE OF t_texttable, g leaded(1) TYPE c CLASS icleventohandier IMF! senttablevo(yy 25 1" eestabiesOliy = 1th. Impmenting events SPeRErePECereTecerecerecec tte cereceerererecerececevecerecerecereecenr cai, trv event_type(20) TYPE c, * Internal table for events that should be registred i_events TYPE cntl_simple events, * Structure for oneline of the table wa_events TYPF cntl_simple_event. c+ * CLASS Le: event_handler DEFINITION * * CLASS lel_event_handler DEFINITION. PUBLIC SECTION. CLASS-METHODS: catch dblelick POR EVENT dblclick OF cl_gui_textedit IMPORTING sender. ENDCLASS. CZASS Lel_event_handler IMPLEMENTATION. METHOD catch_dblelick. DATA: from_line TYPE i, from_pos TYPE i, to_line TYPE i, to_pos TYPE i, wa_texttable TYPE t_texttable. * Used for the sytem event call method cl_gui_cfw->set_new_ok_code exporting new_cade = 'sHO”". * Read the position of the double click CALL METHOD sender->get_selection_pos IMPORTING from_line ~ from_line from_pos - from_pos to_line - to_line to_pos ~ to_pos. * vexts in the Yextedit control can have been changed, so * first reload text from the control into the internal * table that contains text IP NOT g loaded 18 INITIAL. CALL METHOD sender->get_text_as_r3table IMPORTING table = i texttable. * Read the line of the internal table that was clicked READ TABLE i_texttable INDEX from line INTO wa_texttable. IP sy-subre < 0. EXIT, ENDIF, TF wa_texttable+d(1) cs '#". SHIPT wa_texttable. ELSBIF wa_texttable-0(1) NS '*'. SHIFT wa_texttable RIGHT. wa_texttable+0(1) = '*', ENDIF. modify i_texttable from wa_texttable index from line. * Reload texts from h einternal table perform load_texts. ENDIF. cusnttyee = ‘Systen doletictt + NIALL METHOD c1gutefweedispatch. tilet used for aystem au tk _Medute Sratus.o1o0 currur Liestineaynpraayspes ink ENDMETHOD. ENDCLASS. START-OF-SELECTION. CLEAR wa events, REFRESH: i events, S87 SCREEN "100". *~ * + MODULE USER_COMMAND_0100 INBUD + * -* MODULE wser_command_0100 INPUT. CASE ok code. wien ‘EXIT! LEAVE TO SCREEN 0. WHEN SHOW’. event_type = ‘System dolelicx". WHEN 'TMP'. PERFORM Load texts. WHEN OTHERS. * CALL METHOD cl gui cfw: used for system events dispatch. "Not, ENDCASE. ENDMODULE. " USER_COMMAND_0100 INPUT *é— - * *6 Module STATUS 0100 OUTPUT *6- * MODULE status_0100 OUTPUT. * The TextEdit control shoul only be initialized the fizst Eime the * PEO module executes IF editor I$ INITIAL. repid = sy. CREATE OBJECT custom container repid. * Create object for custom container EXPORTING container name = 'MYCONTAINERI' EXCEPTIONS entl_error = 1 entl_systemerror = 2 create_error = 3 lifetime error = 4 Lifetime_dynpro_dynpro_link = 5 others = 6 . IF sy-subre <@ 0. MESSAGE ID sy-msgid TYPE 'T' NUMBER sy-msgno WITH sy-msgvl sy-megv2 sy-msgv3 sy-megv4. ENDIF. * Create obejct. for the TextEditor control CREATE OBJECT editor EXPORTING wordwrap mode cl_gui_textedit-swordwrap_at_fixed_position wordwrap_position ~ Line_length wordwzap_to_linebreak_mode = ¢l_gui_textedit=>true parent custom_container EXCEPTIONS we_evenserevestid = sligei texted: t)evensdoubie_clich, FORM Loads error_cntl_create ~ 1 error_entl_init ~ 2 error_enti_link - 3 error_dp_create = 4 gui_type_not_supported = 5 others = 6 . IF sy-subre <> 0. MESSAGE ID sy-msgid TYPE 'T' NUMBER sy-msgno WITH sy-nsgvl sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. * Link the event handler method to the event and the * TextEdit control, SET HANDLER 1cl_event_handler->catch dbiclick FOR editor. * Register the event in the internal table i_events wa_events-eventid = cl_gui_textedil appl_event = 'X". "This is an application event event_double click. * wa_events- wa_events-appl_event = space. "This is a system event APPEND wa_events TO Levents. * Pass the table to the TextEdit control uding method * set_registred_events CALL METHOD editor->set_registezed events EXPORTING events = i_events. * Create internal table with texts taht can be uploaded to * the TextSdit control APPEND ‘This a method that fills the Texthdit control’ 70 i_texttable. APPEND ‘with a text.' 70 i te: 20 TIMES. APPEND ‘hallo world !' TO 4 ENDDO. ENDIF. ENDMODULE. " STATUS 0100 OUTPUT *6~ * 44 Form Load_texts *4~ * * This form loads the lines of the internal table i texttable inte * the TextEdit control * - * FORM Lead_texts. * Load TextEdit control with texts CALL METHOD editor->set_text_as_r3table EXPORTING table ~ i texttable. IF sy-subre > 0. * Display an error messave EXIT. ENDIF. * All methods that operates on controls are transferred to the frontend * by a RFC calls. the method FLUSH is used to determine when this is * done. CALL METHOD cl_gui_cfw->flush. IF sy-subre > 0. * Display an error message Example 6: Protect a FLUSH in the TextEdit contral and the importance of All methods that operates on controls are transfered to the fronend by AFC call The FLUSH mathod is used to synchronize control axecution and! the frontend, This is very imporan! when working e.g. with export parameters from a method, as the parmeters will not be correct before the FLUSH method has been called The example below portecis selected lines in the TextEdit and uses FLUSH to ‘ensure that the correct parameters are retumed fiom method GET_SELECTION_POS. Note: Instead of using method PROTECT_LINES, the method PROTECT_SELECTION could be used. This method does not need line numbers o” a FLUSH statement Steps + Add.a new pushouton othe screen wih the function code PROTECT. code Add the folowing code to the example * Global variables DATA from_idk TYPE i, to_iox TYPE i index TYPE i MODULE usor_command_0100 INPUT. CASE ok_code. ‘code. WHEN 'PROTECT. PERFORM protect. ENDGASE ENDIF. g_loaded = 'X', ENDFORM. " create texts Example 6: Protect a line in the TextEdit control and the importance of FLUSH All methods that operates on controls are transfered to the fronend by RFC calls. The FLUSH method is used to synchronize control execution and the frontend. This is very important when working e.g. with export parameters from a method, as the parmeters will not be correct before the FLUSH method has been called. The example below portects selected lines in the TextEdit and uses FLUSH to ensure that the correct parameters are returned from method GET_SELECTION_POS. Note: Instead of using method PROTECT_LINES, the method PROTECT_SELECTION could be used. This method does not need line numbers or a FLUSH statement Steps + Add a new pushbutton to the screen with the function code PROTECT. Code Add the following code to the example: * Global variables DATA: from_idx TYPE i, to_idx TYPE i, index TYPE i. MODULE user_command_0100 INPUT. CASE ok_code. code, WHEN 'PROTECT'. PERFORM protect. Example 7: Using multiple controls Inthis example a second TextEdit contol willbe added to the scteen, The new TextEdit contral will ba designed fo act as a clipboard for short texts Steps: + Adda new container to the screen and name t MYCONTAINER2, Code: * protects marked lines in a TextEdit control *-~ + FORM protect. * Determine the area selected by the user CALL METHOD editor->get_selection_pos IMPORTING from_line = from_idx to_line = to_idx EXCEPTIONS error_cnti_call_methed = 1. * Synchronize execution in the control with the ABAP program. * Without this synchronization the variables from_idx and * to_idx will have cbsolutete values (The initial value for * both, are 0 Brror in CALL METHOD cl_gui_efw->flush. IF sy-subre > 0. * Brrormessag flush ENDIF. * Protect the selected lines IF to_idx > from idx. te_idx = to_idx - ENDIF. CALL METHOD editor->protect_lines EXPORTING from line = from idx to_line = te_idx. * The PROTECT SELECTION method could be used instead, eliminating the * need of line numbers and the last FLUSH * call method editor-sprotect_selection. * Flush again to protect immidiately CALL METHOD cl_gui_cfw->flush. IF sy-subre > 0. * Errormessage: flush Error in ENDIF. ENDEORM. " protect Example 7: Using multiple controls In this example a second TextEdit control will be added to the screen. The new TextEdit control will be designed to act as a clipboard for short texts. Steps: + Add a new container to the screen and name it MYCONTAINER2 Code: Insert global datadectaration: implementinga second Serich Texditcontol ‘emsicn TYPE REE 10 el gul textot, Custom container? TYFE REF TO ol gu custom contr. Insert the folowing code in the PEO module Result Insert global datadeciaration: seeeannnneeassnnnennactesennneersniseresnnssestneassstssesss © Implementing a second Scratch TextEdit control *** rena DATA: scratch TYPE REF TO cl_gui_textedit, custom_container2 TYPE REF TO cl_gui_custom_container. Insert the following code in the PBO module: * The SCRATCH Texthdit control *~ scratch IS INITIAL. * Create obejct for custom container? CREATE OBJECT custom container? EXPORTING container_name = 'MYCONTAINER2' EXCEPTIONS entl_error = 1 enti_system error = 2 create error = 3 lifetime_error = 4 Lifeline dynpro dyapro link = 5 others = 6 . IF ay-subre <> 0 MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno WITH sy-nsqvl sy-msgv2 sy-msqv3 sy-msgv4. ENDIF. * Create obejct. for the SCRATCH TextEditor control CREATE OBJECT scratch EXPORTING parent = custom_container? wordwrap_mode = cl_gui_textedit->wordwrap_at_windowborder wordwrap_to_linebreak mode = cl gui _textedit=>true, * Remove the staus bar CALL METHOD soratch->set_statusbar_mode EXPORTING statusbar_mede = cl_gui_textedit=>false. ENDIF. Result: erate DeLcLrex [ici tals ca Teton tet fale woris | Mele wars | fatio wort | fala wars “hallo vere shavis ocr | aalio writ Tatle woras | fatte warts | 2 Dine(Lingwlength) TYPE oy 1 REPORT sapmz_hf_controls1 . 2 3 CONSTANTS: 4 Line_length TYPE i VALUE 254. 5 6 DATA: ok_code LIKE sy ucomm. 7 8 DATA: 9 * Create reference to the custom container 10 custom_container TYPE REF TO cl_gui_custom_container, to the TextEdit control 12 ed: sy-repid. 14 15 11 * Create reference x TYPE REF TO cl_gui_textedit, 13 repid LIKE 16 * Utillity table to load texts 17 18 TYPES: 19 BEGIN OF t_texttable, 20 line(tine length) TYPE c, 21 END OF t_texttable. 22 23 DATA: 24 i_vexttable TYPE TABLE OF t_texttable, fo erates TPE REF To set_new_ok_code 83 EXPORTING new_code = 'SHOW'. 84 85 86 * Read the position of the double click 87 CALL METHOD sender->get_selection pos 88 IMPORTING 89 from_line = from line 90 fom pos = from pos 91 te_line = to_line 92 to_pos = to_pos. 93 94 * Texts in the TextEdit control can have been changed, so 95 * first reload text from the control into the internal 96 * table that contains text 97 IF NO? g_loaded IS INITIAL. 98 CALL METHOD sender->get_text_as_ritable 99 IMPORTING table = i_texttable. 100 * Read the line of the internal table that was clicked 101 READ TABLE i_texttable INDEX from_line INTO wa_texttable. 102 IF sy-subre <> 0. 103 EXIT. 104 ENDIF. 105 106 IF wa_texttable+0(1) cs ‘4, 107 SHIFT wa_texttable. 108 ELSEIF wa_texttable'0(1) NS '*'. 109 SHIPT Wa_texttable RIGHT. 110 wa texttable+0(1) = '*'. 111 ENDIF, 112 MODIFY i_texttable FROM wa_texttable INDEX from_line. 113 * Reload texts from h cinternal table 114 PERFORM load_texts. 115 116 117 ENDIF. 118 119 120 ENDMETHOD. 121 ENDCLASS. 122 123 150 MOOULE user_conmancoio0 :te0T. as EXeCRTING 124 125 START-OF-SELECTION. 126 CLEAR wa_events. 127 REFRESH: i events. 128 129 SET SCREEN '100'. 130 131 132 133 + 134 * MODULE USER_COMMAND_0100 INPUT * 135 + 136 MODULE user_command_0100 INPUT. 137 138 CASE ok code. 139 WIEN ‘EXIT’. 140 LEAVE TO SCREEN 0. 141 WHEN 'SHOW'. 142 event_type = 'Syatem dblelick'. 143 WEEN 'IMP', 144 PERFORM load texts. 145 WEEN "PROTECT'. 146 PERFORM protect. 147 148 WHEN OTHERS. 149 * CALL METHOD cl_gui_cfw->dispatch. "Not used for system events 150 ENDCASE. 151 152 153 ENDMODULE. " USER_COMMAND_0100 INPUT 154 *& 155 *& Module STATUS_0100 OUTPUT 156 *&— 157 MODULE status_0100 OUTPUT. 158 * The TextEdit contrel shoul only be initialized the first time the 159 * PEO module executes 160 IF editor IS INITIAL. 161 repid = sy-repid. 162 * Create obejet for custom container 163 CREATE OBJECT custom container 164 EXPORTING 165 container_name = 'MYCONTATNER?' 166 EXCEPTIONS 167 cntl_error = 1 168 cntl_system_error = 2 169 create_error = 3 170 lifetime_error = 4 171 Lifetime_dynpro_dynpro_link = 5 172 others = 6 173 . Tot tertediteowcrderam es fixed position Bl SET SANDLER Lel_even 174 IP sy-subre <> 0, 175 MBSSAGE ID sy-msgid TYPH 'I' NUMBER sy-mscno 176 WITH sy-msgvl sy-msgv2 sy-msgv3 sy-msgv4. 177 ENDIF. 178 179 * Create obejct for the TextRditor control 180 CREATE OBJECT editor 181 EXPORTING 182 183 wordwrap_mode = 184 cl_gui_textedit=>wordwrap_at_fixed position 165 wordwrap position = line length 186 wordwrap_to_linebreak_mode = cl_gui_textedit=>true 187 parent = custom_container 188 EXCEPTIONS 189 error cntl_create = 1 190 error_entl init = 2 191 error_entl link = 3 192 error dp create = 4 193 gui_type not_supported = § 194 others = 6 195 . 196 IF sy-subre <> 0, 197 MESSAGE ID sy-msgid TYPE 'T' NUMBER sy-msgno 198 WITH sy-msavl sy-msav2 sy-msgv3 sy-msgv4. 199 ENDIF. 200 201 * Link the event handler method Lo the event and the 202 * TextEdit control 203 SET HANDLER lcl_event_handler=>catch_dblclick FOR editor. 204 205 * Register the event in the internal table i_events 206 wa_events-eventid = el_gui_textedit=>event double click. 207 208 * wa events-appl_event = 'x". "This is an application event 209 wa_events-appl_event = space. "This is a system event 210 211 212 APPEND wa_events 70 i events. 213 * Pass the table to the TextEdit contrel uding method 214 * set registred events 215 CALL METHOD editor->set_registered_events 216 EXPORTING events = i_events. 217 218 * Create internal table with texts taht can be uploaded to 219 * the TextEdit control 220 APPEND 'This a method that fills the TextEdit control’ 10 4 texttable. 221 APPEND ‘with a text.'TO i texttable. 222 DO 10 TIMES. 223 APPEND ‘hallo world !" TO i_texttable. 224 ENDDO. 225 ENDIF, 226 227 *. 228 * The SCRATCH TextEdit control 229 *. fosber pode ~ ci_qiutesteditefele. 21 ewowooute, " srarog_o1oo ovreor 230 IF scratch IS INITIAL. 231 * Create obejct for custom container? 232 CREATE OBJECT custom container? 233 EXPORTING 234 container name = 'MYCONTATNER2' 235 EXCEPTIONS 236 cntl_error = 1 237 entl_system_error = 2 238 create error - 3 239 lifetime ezror = 4 240 lifetime dyapro_dynpro_link 5 241 others = 6 242 . 243 IF sy-subre <> 0. 244 MESSAGE ID sy-msgid TYE "I" NUMBER sy-msgno 245 WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. 246 ENDIF. 247 248 * Create obejct for the SCRATCH Textditor control 249 CREATE OBJECT scratch 250 EXPORTING 251 parent = custom container? 252 werdwrap mode = 253 cl_gui_textedit=>wordwrap_at_windowborder 254 wordwrap_to_linebreak_mode cl_gui_textedit->true, 255 256 * Remove the staus bar 257 CALL METHOD sceateh->sel_statusbar mode 258 EXPORTING statusbar mode = false. 259 260 ENDTF. 26° 262 263 ENDMODULE, " sTATUS_0100 cl_gvi_textedit: OUTPUT 264 265 *6 266 *& Form Load_texts 267 *& 268 * This form loads the lines of the internal table i_texttable into 269 * the TextEdit control 270 %@—---—- 271 FORM load texts. 272 273 * Load Textdit control with texts 274 CALL METHOD editor->set_text_as_r3table 275 SXPORTING table = i_texttable. 276 TF sy-subre > 0. 277 * Display an error message 278 EXIT. 279 ENDIF. 280 281 * All methods that operates on controls are transferred to the frontend Be = Sa + telide will have adsolutete values (The initial value tothe ase OF 282 * by a RFC calls. the method FLUSH is used to determine when this is 283 * done. 284 CALL METHOD cl_gui_cfw=>flush. 285 IF sy-subre > 0, 286 * Display an error message 287 ENDIF. 288 g_loaded = 'X'. 289 ENDFORM. create_texts 290 *6: 291 *& Form protect 292 *&- 293 * Protects marked lines in a TextEdit control 294 * 295 FORM protect. 296 * Determine the area selected by the user 297 CALL METHOD editor->get_selection pos 298 IMPORTING 239 from line = from idx 300 to_line = to_idx 301 EXCEPTIONS 302 error_entl_call_methed = 1. 303 304 * Synchronize execution in the control with the ABAP program. 305 * Without, this synchronization the variables from idx and 306 * to idx will have obsolutete values (The initial value for 307 * both, are 0) 308 CALL METHOD cl_gvi_cfw->flush, 309 IF sy-subrc > 0, 320 * Errormessage: Error in flush 311 ENDIF. 312 313 * Protect the lines selected 314 IF to_idx > from idx. 315 to_idx = to_idx - 1, 316 ENDIF. 317 CALL METHOD editor->protect lines 318 EXPORTING 319 from_line = from_idx 320 to_line = to_idx. 321 322 323 * The PROTECT SELECTION method could be used instead, eliminating the 324 * need of line numbers and the last FLUSH 325 326 * call method editor->protect_selection, 327 328 329 * Flush again to protect immidately 330 CALL METHOD el_gui_efw->flush. 331 IF sy-subre > 0, 332 * Errormessage: Error in flush 333 ENDIF.

You might also like