%&$%$32EMHFWV %& $%$32EMHFWV SAP AG 2002 n SAP R/3 n System requirements: SAP R/3, Basis Release 6.10 or later n 2002/Q3 n Material number 5005 4667 &RS\ULJKW &RS\ULJKW6$3$*$OOULJKWVUHVHUYHG 1RSDUWRIWKLVSXEOLFDWLRQPD\EHUHSURGXFHGRUWUDQVPLWWHGLQ DQ\IRUPRUIRUDQ\SXUSRVHZLWKRXWWKHH[SUHVVSHUPLVVLRQRI 6$3$*7KHLQIRUPDWLRQFRQWDLQHGKHUHLQPD\EHFKDQJHG ZLWKRXWSULRUQRWLFH SAP AG 2002 1RWHVRQ7UDGHPDUNV n Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. n Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint®, and SQL Server® are registered trademarks of Microsoft Corporation. n IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®, S/390®, AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation. n ORACLE® is a registered trademark of ORACLE Corporation. n INFORMIX®-OnLine for SAP and INFORMIX® Dynamic ServerTM are registered trademarks of Informix Software Incorporated. n UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group. n HTML, DHTML, XML, and XHTML are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. n JAVA® is a registered trademark of Sun Microsystems, Inc. n JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license for technology developed and implemented by Netscape. n SAP, SAP Logo, R/2, RIVA, R/3, ABAP, SAP ArchiveLink, SAP Business Workflow, WebFlow, SAP EarlyWatch, BAPI, SAPPHIRE, Management Cockpit, mySAP.com Logo, and mySAP.com are trademarks or registered trademarks of SAP AG in Germany and several other countries all over the world. All other products mentioned are trademarks or registered trademarks of their respective companies. &RXUVH3UHUHTXLVLWHV l 3URJUDPPLQJH[SHULHQFH l 6$37(& P\6$37HFKQRORJ\6ROXWLRQ2YHUYLHZ l %& $%$3:RUNEHQFK)RXQGDWLRQVDQG&RQFHSWV l 3URJUDPPLQJH[SHULHQFHLQ$%$3 SAP AG 2002 7DUJHW*URXS l 3DUWLFLSDQWV'HYHORSHUVFRQVXOWDQWV l 'XUDWLRQGD\V SAP AG 2002 1RWHVWRWKHXVHU n The training materials are QRWDSSURSULDWHIRUVHOIVWXG\. 7KH\FRPSOHPHQWWKHFRXUVH LQVWUXFWRU VH[SODQDWLRQV. There is space for you to write down additional information on the sheets. n There may not be enough time during the course to complete all the exercises. The exercises are intended as additional examples of the topics discussed during the course. Participants can also use them as an aid to enhancing their knowledge after the course has finished. &RXUVH2YHUYLHZ &RQWHQWV l &RXUVHJRDO l &RXUVHREMHFWLYHV l &RXUVHFRQWHQW l &RXUVHRYHUYLHZGLDJUDP l 0DLQEXVLQHVVVFHQDULR SAP AG 2002 © SAP AG BC401 1-1 &RXUVH*RDO 7KLVFRXUVHZLOOHQDEOH\RXWR l /HDUQWKHSULQFLSOHVRIREMHFWRULHQWHG SURJUDPPLQJ l /HDUQWKHVWUXFWXUHDQGDSSOLFDWLRQRI $%$32EMHFWV SAP AG 2002 © SAP AG BC401 1-2 &RXUVH2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVFRXUVH\RXZLOOEHDEOHWR l 'HVFULEHDQGXVHWKHPRVWLPSRUWDQWSULQFLSOHV n ,QWHUQDOWDEOHV n &ODVVHVLQKHULWDQFHLQWHUIDFHV n 3RO\PRUSKLVPLQKHULWDQFHDQGLQWHUIDFHV n (YHQWV n ([FHSWLRQKDQGOLQJ n '\QDPLFSURJUDPPLQJ l 'HYHORSSURJUDPVLQ$%$32EMHFWV SAP AG 2002 © SAP AG BC401 1-3 &RXUVH&RQWHQW 3UHIDFH Unit 1 Unit 2 Unit 3 Unit 4 Unit 5 Unit 6 Unit 7 Unit 8 Unit 9 Unit 10 &RXUVH2YHUYLHZ 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO 8VLQJ,QWHUQDO7DEOHV &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD ,QWURGXFWLRQWR2EMHFW2ULHQWHG3URJUDPPLQJ $QDO\VLVDQG'HVLJQ 3ULQFLSOHVRI2EMHFW2ULHQWHG3URJUDPPLQJ ,QKHULWDQFH &DVWLQJ ,QWHUIDFHV SAP AG 2002 © SAP AG BC401 1-4 &RXUVH&RQWHQW Unit 11 Unit 12 Unit 13 Unit 14 Unit 15 (YHQWV *OREDO&ODVVHVDQG,QWHUIDFHV 6SHFLDO7HFKQLTXHV ([FHSWLRQ+DQGOLQJ '\QDPLF3URJUDPPLQJ $SSHQGL[ SAP AG 2002 © SAP AG BC401 1-5 &RXUVH2YHUYLHZ,QWHJUDWLRQLQ&RXUVH&RQWHQW SAP AG 2002 © SAP AG BC401 1-6 0DLQ%XVLQHVV6FHQDULR l $WUDYHODJHQWPDLQWDLQVLWVFRQQHFWLRQVWR EXVLQHVVSDUWQHUVVXFKDVDLUOLQHVFDUKLUH FRPSDQLHVDQGKRWHOV SAP AG 2002 © SAP AG BC401 1-7 7HFKQLFDO1DPHV l 3DFNDJH%& l 1DPLQJFRQYHQWLRQVIRUSURJUDPREMHFWV n 'HPRQVWUDWLRQV 6$3%&B[[['B n 0RGHOVROXWLRQV 6$3%&B[[[6B n &RS\WHPSODWHV 6$3%&B[[[7B [[[LVWKHLQGLYLGXDOXQLWFRGH SAP AG 2002 n Unit codes: Unit 2: Unit 3: Unit 4: Unit 7: Unit 8: Unit 9: Unit 10: Unit 11: Unit 12: Unit 13: Unit 14: Unit 15: © SAP AG DTO TAB CAL AIR INH CAS INT EVE CLS SPC EXC DYN BC401 1-8 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO &RQWHQWV l 'DWDREMHFWVLQSURJUDPV l (OHPHQWDU\GDWDREMHFWV l 6WUXFWXUHV l &KDUDFWHUVWULQJSURFHVVLQJLQ8QLFRGH SAP AG 2002 © SAP AG BC401 2-1 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 8VHHOHPHQWDU\GDWDREMHFWVDQGVWUXFWXUHV DSSURSULDWHO\ l 8VHQXPHULFGDWDW\SHVDSSURSULDWHO\ l 8VHDXWRPDWLFW\SHFRQYHUVLRQVDSSURSULDWHO\ l 7DNHWKHVSHFLDOIHDWXUHVRIFKDUDFWHUVWULQJ SURFHVVLQJLQ8QLFRGHLQWRDFFRXQW SAP AG 2002 © SAP AG BC401 2-2 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO ,QWHJUDWLRQLQ&RXUVH&RQWHQW !#"!$%'& $ &!( $*) SAP AG 2002 © SAP AG BC401 2-3 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO ,QWURGXFWLRQ ,QWURGXFWLRQ (OHPHQWDU\'DWD2EMHFWV (OHPHQWDU\'DWD2EMHFWV 6WUXFWXUHV 6WUXFWXUHV 6SHFLDO)HDWXUHVLQ8QLFRGH 6SHFLDO)HDWXUHVLQ8QLFRGH SAP AG 2002 © SAP AG BC401 2-4 5HYLVLRQ'HILQLQJ'DWD2EMHFWV /RFDOW\SHV 7<3(6W\SHBQDPH7<3( 3UHGHILQHG $%$3W\SHV G W L S I Q VWULQJ F [VWULQJ [ '$7$GRBQDPH7<3(W\SHBQDPH '$7$ *OREDO W\SHV '$7$GRBQDPHBQHZ/,.(GRBQDPH '$7$ SAP AG 2002 n Data objects are usually defined with the '$7$statement as follows. After the name of the data object, a a fully-specified type is assigned to it using the 7<3( addition. The type is linked to the data object statically and cannot be changed at runtime. n There are other syntax variants available (for historical reasons). Note however, that some of these historical variants are no longer supported in ABAP Objects. For further information, refer to the keyword documentation for the '$7$ statement. n All types are based on predefined ABAP types, which will be discussed in greater detail in the following slide. Some of these ABAP types are fully specified and can be used to type data objects directly. Other types need to be modified to include the length, and in some cases the number of decimal places so that they are fully specified. These are the simplest examples of user-defined types. n You can create complex structured types of any level of complexity, based on elementary types. n You can also define types centrally in the $%$3'LFWLRQDU\ You can then use these JOREDOW\SHV in all appropriate Repository objects in the system. © SAP AG BC401 2-5 3UHGHILQHG$%$37\SHV 'DWD W\SH 1XPHULF )L[HGOHQJWK L I S ,QWHJHU /HQJWKLQE\WHV )ORDWSRLQWQXPEHU 3DFNHGQXPEHU &KDUDFWHUVWULQJW\SH Q F G W +H[DGHFLPDO [ 9DULDEOH OHQJWK 'HVFULSWLRQ 1XPEHUVHTXHQFH 7LPH +H[DGHFLPDOFRGH &KDUDFWHUVHTXHQFH 'DWH &KDUDFWHUVWULQJW\SHKH[DGHFLPDO VWULQJ [VWULQJ &KDUDFWHUVHTXHQFH +H[DGHFLPDOFRGH $WWULEXWHV 'LIIHULQ •5XOHVIRUVWRUDJH •9DOXHUDQJH •$ULWKPHWLFXVHG &KDUDFWHUVWULQJRSHUDWLRQV DOORZHGIRUDOOW\SHV GDWHFDOFXODWLRQV WLPHFDOFXODWLRQV %LWRSHUDWLRQV 5XQWLPHV\VWHPDGMXVWVOHQJWK G\QDPLFDOO\ SAP AG 2002 n The following ABAP types are fully specified and can be used directly to type data objects: G, W, L, I, VWULQJ, and [VWULQJ. A special feature of the VWULQJ and [VWULQJ types is that their length is adjusted dynamically at runtime. Thus, for these two types, length is not a component of the type. n The following ABAP types are not fully specified, so you must include additional information before you use them to define data objects: é F, Q, and [ Length needs to be added. Permitted values: to characters. If you do not declare a length when you define a data object, the system assigns the default length of . é S You must extend the type to include the length, and number of decimal places, Permitted length: to bytes. If you do not declare a length when you define a data object, the system assigns the default length of bytes (that is, 15 digits) and decimal places. n The type also contains information on how the data is stored, what range of values is allowed, what operations can be performed on the data, and what sort of arithmetic is used (if the data object is suitable for use in calculations). We will deal with this topic in greater detail later in this unit. © SAP AG BC401 2-6 7\SH*URXSVLQWKH$%$3'LFWLRQDU\ 1DPHRIW\SHJURXS 8SWRFKDUDFWHUV HDFKW\SHQDPHDQG FRQVWDQWQDPH VWDUWVZLWKWKHQDPHRI WKHW\SHJURXS (DFKW\SHJURXSZKRVH W\SHVDQGFRQVWDQWV\RX ZDQWWRXVHPXVWEHVSHFLILHG LQWKH$%$3SURJUDP 7\SHJURXS]P\WS ]P\WS 7<3(322/]P\WS &2167$176]P\WSBFRQVWBQDPH ]P\WS ]P\WS >7<3(6]P\WSBW\SHBQDPH@ ]P\WS >7<3(6]P\WSBW\SHBQDPH@ 8VLQJDFRQVWDQW $%$3SURJUDP 7<3(322/6]P\WS ]P\WS 7<3(322/6 ]P\WS >'$7$YDU7<3(]P\WSBW\SH@ ]P\WS ,)YDU ]P\WSBFRQVWBQDPH (1',) SAP AG 2002 n You must use a type group to define global constants. The name of the type group can contain up to 5 characters. n You define constants in the type group using the &2167$176 statement, just as in an ABAP program. You only have to adhere to the following namespace convention: All constants (and type names) must have the name of the type group as a prefix. You can use either a global Dictionary type or a predefined ABAP type as a valid type. n To be able to use the types of a type group in a program, you must refer to the type group using the 7<3(322/6 statement. After this line in the program, you can then use all the constants in the type group. n You can also define global data types in a type group. Before SAP R/3 Basis Release 4.5, this was the only way to define complex global data types. © SAP AG BC401 2-7 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO ,QWURGXFWLRQ ,QWURGXFWLRQ (OHPHQWDU\'DWD2EMHFWV (OHPHQWDU\'DWD2EMHFWV 6WUXFWXUHV 6WUXFWXUHV 6SHFLDO)HDWXUHVLQ8QLFRGH 6SHFLDO)HDWXUHVLQ8QLFRGH SAP AG 2002 © SAP AG BC401 2-8 ,QWHJHUVDQG,QWHJHU$ULWKPHWLF /HQJWKE\WHV '$7$FRXQWHU7<3(L9$/8( l l 9DOXHUDQJH>@ LQW LQWLQWLQW l ,QWHJHU$ULWKPHWLF $OOLQWHUQDODX[LOLDU\ILHOGVDUHLQWHJHUV ,QWHULPUHVXOWVDUHURXQGHG $ULWKPHWLFRSHUDWLRQVIRU LQWHJHUV LQW LQW LQW LQW ,QWHJHUDX[LOLDU\YDULDEOH ',9 02' $GGLWLRQ 6XEWUDFWLRQ 0XOWLSOLFDWLRQ 'LYLVLRQ ,QWHJHUGLYLVLRQ 5HPDLQGHULQWHJHUGLY 3RZHU SAP AG 2002 n In integer arithmetic, the system always rounds to the appropriate decimal place. So, for example: '$7$LQW7<3(LLQW " result: 0 LQW " result: 1 n Calculations performed using integer arithmetic are faster than calculations using fixed point or floating point arithmetic. n For further information on calculations performed on integers, refer to the keyword documentation for the &20387( statement. © SAP AG BC401 2-9 3DFNHG1XPEHUVDQG)L[HG3RLQW$ULWKPHWLF '$7$SHUFHQWDJH 7<3(S'(&,0$/69$/8( '(&,0$/6 /HQJWKLQE\WHV QE\WHVFRUUHVSRQGWR QGLJLWV 1XPEHURIGHFLPDO SODFHV )L[HGSRLQWDULWKPHWLF OLNHXVLQJSDSHUDQGSHQFLO 1XPEHU ,QWHUQDOUHSUHVHQWDWLRQ +-,/. 01.32547658 9:<;>=3?@BAC236 D . 0FE l3HUPLWWHGOHQJWKWRE\WHV WRGLJLWV l1XPEHURIGHFLPDOSODFHVQXPEHURIGLJLWVPD[ l([DPSOH/HQJWKE\WHVGHFLPDOSODFHV ë9DOXHUDQJH>@ SAP AG 2002 n The length of packed numbers is given in bytes. The connection between value range and length is derived from the internal representation: Each decimal digit is represented by a half-byte. The last byte is reserved for the plus or minus sign. n The number of decimal places is defined using the '(&,0$/6 addition. The maximum number of decimal places is either 15 or the length of the number minus 1 (that is, there must be at least one digit before the comma). n In user dialogs, decimal numbers are formatted according to the settings in the user master record. n Decimal point-aligned fixed point arithmetic is used as default for calculations. Packed numbers are thus well-suited to business calculations, where the correct rounding for the specified number of decimal places is very important. The algorithm for this arithmetic is similar to using "pencil and paper". n The system always uses packed numbers of maximum length for interim results. n You can switch off fixed point arithmetic in the program attributes. If you do, the '(&,0$/6 addition when defining a packed number only affects the output of the number. Internally, all numbers are interpreted as integers, regardless of the position of the decimal point. The fixed point arithmetic option is always selected by default. You should DOZD\V accept this value and use packed numbers for business calculations. © SAP AG BC401 2-10 )ORDWLQJ3RLQW$ULWKPHWLF _ _ - 2QO\ELWVDYDLODEOH 1,5 = 1×20 + 1×2 1 1 =1 + 2 _ _ -3 _ _ _ -6 -7 -10 -11 0,15 = 1×2 + 1×2 + 1×2 + 1×2 + 1×2 + Λ 1 1 1 1 1 = + + + + + 8 128 1024 2048 Λ 64 ≈ = 0,125 + Λ = = = 0,140625 +Λ 2QO\IRU DSSUR[LPDWLRQV 0,1484375 +Λ 0,1494140625 + Λ 01499023437 Λ = SAP AG 2002 n Unlike packed numbers, floating point numbers are represented using sums of binary fractions. Floating point numbers are also normalized, and both the exponent and the mantissa are stored in binary form. This representation complies with the IEEE norm for double precision floating point numbers. The floating point operations of the relevant processors are used for calculations. Since algorithms are converted to binary, inaccuracies can occur. Therefore, floating point numbers are QRW suitable for business calculations. ([DPSOH You want to calculate 7.72% of 73050 and display the result accurate to two decimal places. The answer should be 5310.74 (73050 * 0.0727 = 5310.7735). The program, however: '$7$IORDW7<3(ISDFN7<3(S'(&,0$/6 IORDW UHVXOW( SDFN IORDW:5,7(SDFNUHVXOW n n <RXVKRXOGWKHUHIRUHRQO\XVHIORDWLQJSRLQWQXPEHUVIRUDSSUR[LPDWLRQV:KHQ\RXFRPSDUH QXPEHUVDOZD\VXVHLQWHUYDOVDQGDOZD\VURXQGDWWKHHQGRI\RXUFDOFXODWLRQV The DGYDQWDJHRIIORDWLQJSRLQWQXPEHUV is the large value range: It comprises numbers from is, from 2,2250738585072014E-308 to 1,7976931348623157E+308 including both positive and negative numbers as well as zero.In addition, you must use floating point numbers for special aggregation functions of the 6(/(&7 statement. © SAP AG BC401 2-11 6XPPDU\5HFRPPHQGDWLRQVIRU8VLQJ1XPHULF 'DWD7\SHV 5HTXLUHG ,QWHJHUVRQO\ 5HFRPPHQGHGSUHGHILQHG$%$3GDWDW\SH 7\SHL VLQFHFDOFXODWLRQVXVLQJLQWHJHUDULWKPHWLFDUH IDVWHVW 'HFLPDOQXPEHUVIRU EXVLQHVVFDOFXODWLRQV 7\SHS 'HFLPDOQXPEHUVIRU URXJKFDOFXODWLRQV SHUIRUPHGRQYHU\VPDOO RUYHU\ODUJHQXPEHUV 7\SH) SAP AG 2002 n 1RWH The results of the following functions have the data type I: é Trigonometric functions:FRV, DFRV,VLQ, DVLQ, WDQ, DWDQ é Hyperbolic functions: WDQK, VLQK, FRVK é Exponential functions (base e): H[S é Natural logarithms (base e): ORJ é Logarithms (base 10): ORJ é Square root: VTUW © SAP AG BC401 2-12 $ULWKPHWLFDQG0L[HG([SUHVVLRQV l)L[HGSRLQWDULWKPHWLFLVWKHGHIDXOW l,QWHJHUDULWKPHWLFLVRQO\XVHGLIDOOWKHFRPSRQHQWVDUHLQWHJHUV l)ORDWLQJSRLQWDULWKPHWLFLVXVHGLIDWOHDVWRQHFRPSRQHQWLVDIORDWLQJSRLQWQXPEHU l$OOFRPSRQHQWVDUHFRQYHUWHGWRWKHUHOHYDQWGDWDW\SH l$IWHUWKHFDOFXODWLRQDOODUHFRQYHUWHGWRWKHUHVXOWW\SH ([DPSOH S'(&,0$/6 U L L I F D E ( ( ( ,QWHULPUHVXOW →)ORDWSRLQWDULWKPHWLF ↓ ó &RQYHUVLRQDIWHUI DQGFDOFXODWLRQ ( ↓ ì &RQYHUVLRQDIWHU S'(&,0$/6 SAP AG 2002 n An arithmetic expression may contain any data types that are convertible into each other and into the type of the result field. n The system converts all the values into one of the three numeric data types (L, S, or I), depending on the data types of the operands. The ABAP runtime system contains an arithmetic for each of the three data types. The system then performs the calculation and converts it into the data type of the result field. n This may mean that the same arithmetic expression leads to different results when performed on different combinations of data types. n It is also possible for an arithmetic expression to have RQO\FKDUDFWHUVWULQJW\SH data objects, as long as their contents are appropriate. The values are converted to numeric type objects. Bear in mind that conversions affect performance. Wherever possible, choose a data type that does QRW require runtime conversion. n If an arithmetic expression contains numeric literals, the choice of arithmetic depends on the size of the number: If the number is within the value range for the data type L, the numeric literal is interpreted as an integer. If the value of the literal is greater than 2147483647, it is interpreted as a packed number. ([DPSOH '$7$LQW7<3(LLQW "result: 9 LQW "result: 10 © SAP AG BC401 2-13 3UHGHILQHG$%$37\SHVIRU&KDUDFWHU6WULQJV 'HVFULSWLRQ /HQJWK 9DOXHUDQJH &DOFXODWLRQV )RUPDWWLQJ RSWLRQV 7\SHW 7\SHG 7LPH 'DWH GLJLWV ++0066 GLJLWV <<<<00'' FKDUDFWHUV %\FORFN 7LPH DULWKPHWLF ++0066 7\SHQ 7\SHF 7\SHF 6HTXHQFH )L[HGOHQJWK RIGLJLWV FKDUVWULQJ %\*UHJRULDQ FDOHQGDU 'DWH DULWKPHWLF 'LJLWV &RQYHUVLRQ FKDUDFWHUV 7\SHVWULQJ 7\SHVWULQJ &KDUVWULQJ RIYDULDEOH OHQJWK 9DULDEOH 'HSHQGVRQFRGHSDJH 'HSHQGVRQFRGHSDJH &RQYHUVLRQ &RQYHUVLRQ %DVHGRQ XVHUGHIDXOW YDOXHV SAP AG 2002 n The value range of each string depends on the code page, which contains all the supported characters in form of a table. Internally, each character is represented by a code number. When the system outputs the character, it uses the code page to convert this number. To find the code page valid in a given system, choose 7RROV →&&06→6SRRO$GPLQLVWUDWLRQ→)XOO$GPLQLVWUDWLRQ→&KDUDFWHU 6HWV. n The initial value of each character string with fixed length is a space character. n Numeric strings are represented internally as character strings. Note, however, that only digits are permissible as characters. When character strings are assigned to numeric strings, the system ignores letters and only copies the digits (right-aligned). Missing characters are filled with zeros. n The initial value of each character in a numeric string is a zero. n n n n Only sequences of digits are valid for values of type G. These digits form a meaningful date, which complies with the Gregorian calendar. The first four digits represent the year, the next two the month and the last two the date. For performance reasons however, the object is only checked if it is an input field on a screen or selection screen. The initial value of a date is . The formatting options are determined by the user settings. For values of type W, a sequence of digits is only valid if it can be interpreted as a time on the 24-hour clock. The rules for interpreting the value are analogous to those used for dates. The initial value of a time is . © SAP AG BC401 2-14 2YHUYLHZ&KDUDFWHU6WULQJ3URFHVVLQJ ),1' 5(3/$&( 75$16/$7( 6+,)7 &21'(16( 29(5/$< &21&$7(1$7( 63/,7 % " GIHKJLBMN'O<PQROJCSTVUXWZY $%$3 $%$3 $%$3 $%$3 $3 $%3 $$$$ %%$3 DEDS %$3 $3 $%$3 $% $3 $%$3 $%&$3 $% $3 'HVFULSWLRQDQGQRWHV 6HDUFKLQDFKDUDFWHUVWULQJ 3RVLWLRQRIVHDUFKVWULQJ XVLQJ0$7&+2))6(7RIIDGGLWLRQ 5HSODFHILUVWRFFXUUHQFH 5HSODFH 5HSODFHDOORFFXUUHQFHV 0RYH 5HPRYHVSDFHFKDUDFWHUV 5HPRYH 2YHUZULWH 2YHUZULWH6SDFHVDUHRYHUZULWWHQ E\FKDUDFWHUVIURPWKHVHFRQG FKDUDFWHUVWULQJ &RQFDWHQDWH &RQFDWHQDWHVHYHUDO FKDUDFWHUVWULQJV 6SOLWDFKDUDFWHUVWULQJ 6SOLW SAP AG 2002 n n n n n n Note for ),1'statement (search in a character string): There are special comparison operators for strings, which you can use in logical expressions in a query (,)) to search more flexibly for character sequences in a character string. For more information, see the keyword documentation for ,). For every statement, the operands are treated like type F fields, regardless of their actual field type. No internal type conversions take place. All of the statements apart from 75$16/$7(and &21'(16(set the system field V\VXEUF. (6($5&+also sets the system field V\IGSRV with the offset of the character string found.) All of the statements apart from 6($5&+ are case-sensitive. To find out the occupied length of a string, use the standard function 675/(1 For the 63/,7statement there is the variant 63/,7,1727$%/(<itab>, which you can use to split the character string dynamically. You do not need to specify the number of parts into which the string should be split. © SAP AG BC401 2-15 $FFHVVLQJ3DUWVRI)LHOGV VWDWHPHQW!ILHOG!RII! OHQ! 3RVVLEOHZLWKDQ\ FKDUDFWHUW\SHILHOG 5(3257 3$5$0(7(56 SDBVWU /2:(5&$6( SDBSRV7<3(L SDBOHQ7<3(L :5,7(SDBVWUSDBSRV SDB SDB SDBSRV SDBOHQ SDBOHQ [\I\<\[5]<^[__3`a]I^Ib<\<b/\ Y/Y<Y<Y<Y/Y SAP AG 2002 n In DQ\ statement that operates on a FKDUDFWHUW\SH field, you can address part of the field or structure by specifying a starting position and a number of characters. If the field lengths are different, the system either truncates the target or fills it with initial values. The source and target fields must have the type [, F, Q, G, W, or 675,1*You can also use structures. ([DPSOH 029(<field1>+<off1> <len1> 72<field2>+<off2> <len2> This statements assigns len1> characters of field <field1> starting at offset <off1> to <len2> characters of <field2> starting at offset <off2>. © SAP AG BC401 2-16 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO ,QWURGXFWLRQ ,QWURGXFWLRQ (OHPHQWDU\'DWD2EMHFWV (OHPHQWDU\'DWD2EMHFWV 6WUXFWXUHV 6WUXFWXUHV 6SHFLDO)HDWXUHVLQ8QLFRGH 6SHFLDO)HDWXUHVLQ8QLFRGH SAP AG 2002 © SAP AG BC401 2-17 'HILQLQJ6WUXFWXUHVZLWK/RFDO7\SHV 'HILQLWLRQRIDVWUXFWXUHW\SH 7<3(6 7<3(6 %(*,12) VBQDPHBW\SH %(*,12)VBQDPHBW\SH SUHQDPH 7<3(F VXUQDPH 7<3(F WLWOH 7<3(F (1'2)VBQDPHBW\SH (1'2) 'HILQLWLRQRIDVWUXFWXUHZLWK LPSOLFLWW\SHFRQVWUXFWLRQ '$7$ '$7$ %(*,12) VBQDPH %(*,12)VBQDPH SUHQDPH 7<3(F VXUQDPH 7<3(F WLWOH 7<3(F (1'2)VBQDPH (1'2) VBQDPH 'HILQLWLRQRIDVWUXFWXUHZLWK UHIHUHQFHWRDXVHUGHILQHGW\SH '$7$ VBQDPH7<3(VBQDPHBW\SH VBQDPH VBQDPHBW\SH $OWHUQDWLYHV 67$572)6(/(&7,21 VBQDPHSUHQDPH 6PLWK VBQDPH VBQDPHVXUQDPH -RKQ VBQDPH SAP AG 2002 n As with elementary data objects, you can define structures in two ways: é First, define a structure type explicitly using the 7<3(6 statement. To do this, enter the name of the structure after %(*,12) and then list the definitions of all the components. End the definition of the structure type using (1'2). You then define the structured data object with the '$7$ statement, using your own user-defined structure type. é Define the data object directly using the '$7$ statement. The syntax is similar to the definition of a structure type. If you use this option, the corresponding structure type is defined implicitly at the same time. n In both cases, the type is defined locally. Bear in mind that you can also use globally defined types instead. n You address components of structures using: structure_namecomp_name. For this reason, you should avoid using hyphens in variable names. © SAP AG BC401 2-18 'HILQLQJ1HVWHG6WUXFWXUHVZLWK/RFDO7\SHV 7<3(6 %(*,12)VBQDPHBW\SH VBQDPHBW\SH SUHQDPH 7<3(F VXUQDPH 7<3(F WLWOH 7<3(F (1'2)VBQDPHBW\SH 6WUXFWXUHW\SH VBQDPHBW\SH SUHQDPH VXUQDPH WLWOH '$7$ %(*,12)VBDGGUHVV QDPH7<3(VBQDPHBW\SH VBQDPHBW\SH VWUHHW 7<3(F FLW\ 7<3(F (1'2)VBDGGUHVV VBDGGUHVV VBDGGUHVVQDPHVXUQDPH 6PLWK VBDGGUHVVFLW\ /RQGRQ 1HVWHGVWUXFWXUH QDPH VWUHHW FLW\ SUHQDPH VXUQDPH WLWOH $SSOLFDWLRQ /RJLFDOVXEJURXSLQJ RIGDWD SAP AG 2002 n You can define nested structures by assigning a structure type to a component ZLWKLQ a structure type. n You can address this substructure as a whole using the component name: structure_namesubstructure_name. n You can also address individual components in the VXEstructure: structure_name-substructure_name-comp_name. n Structures can be nested to any level you wish. n You can also integrate components of a dynamic type in a structure. This can either be an elementary data object of variable length (VWULQJ or [VWULQJ),an internal table, or a reference. These structures are known as GHHS structures. n There are constraints on how such deep structures can be used. For instance, a deep structure cannot be used DVDZKROH in the,172 clause of the 6(/(&7 statement. (Instead, each component must be listed separately). Offset operations are also not appropriate. For more information, refer to SAP Note 176336. © SAP AG BC401 2-19 8VLQJ1DPHG,QFOXGHV '$7$ %(*,12)WBOLQHW\SH VBQDPHBW\SH SUHQDPH 7<3(F VXUQDPH 7<3(F WLWOH 7<3(F (1'2)VBQDPHBW\SH 6WUXFWXUHW\SH VBQDPHBW\SH SUHQDPH VXUQDPH WLWOH '$7$ %(*,12)VBDGGUHVV ,1&/8'(6758&785(VBQDPHBW\SH ,1&/8'(6758&785( VBQDPHBW\SH $6QDPH $6 '$7$ VWUHHW 7<3(F FLW\ 7<3(F (1'2)VBDGGUHVV VBDGGUHVVQDPHVXUQDPH 6PLWK RU VBDGGUHVVVXUQDPH 6PLWK 6WUXFWXUHZLWKQDPHGLQFOXGH VBDGGUHVV SUHQDPH VXUQDPH WLWOH VWUHHW FLW\ QDPH 8VH /RJLFDOVXEJURXSGHVLUHGEXWQHVWHG VWUXFWXUHVQRWWHFKQLFDOO\SRVVLEOH SAP AG 2002 n In some cases, you cannot use nested structures, for example: é Because you can only define database tables with flat line types é In situations where user dialogs with a table-type display can only contain simple structures (such as in the SAP List Viewer or Table Control) n In situations like these, you may still want to group parts of the structure and address it as a whole. You do this using named includes: é You can include a substructure in another structure, and give this substructure a name: '$7$%(*,12)structure_name ,1&/8'(6758&785(substructure_type$6name '$7$ (1'2)structure_name é You can address this substructure using structure_name-name. You can address the fields in the substructure using structure_name-name-comp_name or directly using structure_name-comp_name. Technically, however, this structure is QRWnested. é If naming conflicts occur - for example, if you want to include the same substructure twice - you can append another name to the component names using 5(1$0,1*. For further information, refer to the keyword documentation for the ,1&/8'(6758&785( statement. © SAP AG BC401 2-20 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO ,QWURGXFWLRQ ,QWURGXFWLRQ (OHPHQWDU\'DWD2EMHFWV (OHPHQWDU\'DWD2EMHFWV 6WUXFWXUHV 6WUXFWXUHV 6SHFLDO)HDWXUHVLQ8QLFRGH 6SHFLDO)HDWXUHVLQ8QLFRGH SAP AG 2002 © SAP AG BC401 2-21 8QLFRGH2YHUYLHZ 3UHYLRXVSUREOHPV l l 0L[WXUHRIGLIIHUHQWLQFRPSDWLEOHFKDUDFWHUVHWVLQRQHFHQWUDO V\VWHP 'DWDH[FKDQJHEHWZHHQV\VWHPVZLWKLQFRPSDWLEOHFKDUDFWHUVHWV D D " 8QLFRGH " " 6 6ROXWLRQ8QLFRGH l 21(FRGHSDJHWKDW FRPSULVHVDOONQRZQ FKDUDFWHUV l (YHU\FKDUDFWHULVJHQHUDOO\ GLVSOD\HGE\WZRE\WHV SAP AG 2002 n To be able to work with Unicode, you must have a Unicode-compatible SAP System installed that itself has a corresponding operating system and database. The ABAP programs must also be Unicode-compatible. n In Unicode programs, other syntax rules apply than in non-Unicode programs. This is due to the difference between the length in bytes and the number of characters in a character set in Unicode. Existing programs are affected by a conversion to Unicode if an explicit or implicit assumption is made about the internal length of a character. To execute the relevant syntax checks, you must check 8QLFRGH&KHFNV$FWLYHunder program attributes. n In a Unicode system, you can only execute programs that have the Unicode flag set. If the Unicode flag is set for a program, the syntax check and program are executed in accordance with the rules described in the Unicode online help (irrespective of whether it is a Unicode or a non-Unicode system). n If the Unicode flag is not set, the program can only be executed in a non-Unicode system. For such programs, the Unicode-specific changes of syntax and semantics do not apply. However, you can use all language enhancements introduced in connection with the conversion to Unicode. © SAP AG BC401 2-22 &KDUDFWHU7\SHDQG%\WH7\SH7\SHV &KDUDFWHUW\SHW\SHVLQ8QLFRGHSURJUDPV 2QO\FRPSRQHQWV ZLWKWKHW\SHV cndDQGt G F W Q E\WHW\SH &KDUDFWHUW\SH VWUXFWXUHW\SHV [VWULQJ VWULQJ [ 'LIIHUHQFHEHWZHHQE\WHSURFHVVLQJDQGFKDUDFWHUSURFHVVLQJ '$7$FBILHOG 7<3(F9$/8( +8*2 [BILHOG 7<3([9$/8( (%$ 6+,)7FBILHOG%<3/$&(6>,1&+$5$&7(502'(@ 6+,)7[BILHOG%<3/$&(6,1%<7(02'( cedfg hi j monqpsr p}r d~d kdflg h5i j t<uvwx/v y1z xvey{z|||| SAP AG 2002 n In Unicode programs, the following data types are interpreted as character-type: F, Q, G, W, VWULQJ as well as structure types, that directly or in substructures only contain components with types F, Q , G and W. In non-Unicode systems, a character of this type is one byte and in Unicode systems, it is as long as corresponds with the length of a character on the relevant platform. Variables of the types [and [VWULQJ are described as byte-type. n The character string processing (for which, previously, all arguments were implicitly interpreted as type Ffields) is separated into string processing for character-type and byte-type arguments. n n In the case of the string processing for character-type arguments, the single fields must be typeF, Q, G, W, or VWULQJ; character-type structures are also permitted. If arguments of another type are transferred, this triggers a syntax or runtime error. The ;variants of the string statement are distinguished from the character string commands by the ,1%<7(02'(addition. For the character string variants, ,1&+$5$&7(502'(is an optional addition. If the ,1%<7(02'(addition is specified, only ;fields and ;strings are permitted as arguments. If arguments of another type are transferred, this triggers a syntax or runtime error. © SAP AG BC401 2-23 )XQFWLRQVDQG&RPSDULVRQ2SHUDWRUV /HQJWKLQ FKDUDFWHUV )XQFWLRQV &RPSDULVRQ RSHUDWRUV &KDUDFWHUW\SHW\SH 675/(1 675/(1 &11$1613 /< 5{F<eCK<BICBCCB 5{F<FXeCK<BIC* /¡ ¢/£¤¥CIK§¦ ¨¥CIC¡ ¡¡¡ ©¥¢I£¡ %\WHW\SHW\SH ;675/(1 &2&$&6&3 ([DPSOHV /HQJWKLQ E\WHV %<7(&2%<7(&$ %<7(&6%<7(&1 %<7(1$%<7(16 /1 «ª<F¬<­1<*F®/ ¤ª B{IF¯°F±B'²¥± 7³B /­´¤K<µ¬a¡ I­B´·¶¹¸ºIB»CBB©¼½ª'7C¬I­KI¾¿¡ SAP AG 2002 n n n n The operators &2, &1, &$, 1$, &6, 16, &3, 13 are available for comparing the contents of character string type data objects (for syntax and semantics, see keyword documentation). As with the statements for string processing, these operators require single fields of type FQ, G, W, or VWULQJ as arguments. Again, character-type structures are also permitted. The ;variants of the string comparison operators are distinguished from the character string variants by the %<7(- prefix. For this operation, only ; fields and fields of the type [VWULQJ are allowed as arguments. The 675/(1function only works with character-type fields and returns the length in characters. With Ffields, only the so-called occupied length is relevant, that is, unlike with strings, trailing blanks are not counted. The ;675/(1 function is available for the length of byte sequences. For ; strings, ;675/(1 returns the current length and for ;fields, the defined length in bytes, where null bytes at the end of fields are counted. © SAP AG BC401 2-24 &RPSDWLELOLW\DQG&RQYHUVLRQ À 1ÂÁ·BÄÃÅ¡ ö¤Á ¡ :KHQDUHWZRW\SHVFRPSDWLEOH" 7ZRHOHPHQWDU\W\SHVDUHFRPSDWLEOHZKHQWKH\ KDYHH[DFWO\WKHVDPHW\SHDQGOHQJWK W\SH OHQJWK DQGLQWKH FDVHRISDFNHGQXPEHUVWKHVDPHQXPEHURI GHFLPDOSODFHV GHFLPDOSODFHV 7ZRVWUXFWXUHW\SHVDUHFRPSDWLEOHZKHQWKH\KDYHWKH VDPHVWUXFWXUHDQGWKHLUFRPSRQHQWVDUH VDPHVWUXFWXUH FRPSRQHQWVDUHFRPSDWLEOH URZW\SHV 7ZRWDEOHW\SHVDUHFRPSDWLEOHLIWKHLUURZW\SHVDUH FRPSDWLEOH FRPSDWLEOHDQGWKHLUNH\GHILQLWLRQVDQGWDEOHW\SHV FRPSDWLEOH NH\GHILQLWLRQV WDEOHW\SHV DUHWKHVDPH l l 1RFRQYHUVLRQWDNHVSODFHLIW\SHFRPSDWLEOHGDWDREMHFWVDUHDVVLJQHG ,IQRQW\SHFRPSDWLEOHGDWDREMHFWVDUHDVVLJQHGFRQYHUVLRQGRHVWDNH SODFHLIDFRQYHUVLRQUXOHLVGHILQHG SAP AG 2002 n If two data types are not compatible but there is a conversion rule, the system converts the source object into the type of the target object when you assign values, perform calculations, or compare values. n For a full list of all conversion rules, refer to the ABAP syntax documentation for the 029( statement. n If there is no conversion rule defined for a particular assignment, the way in which the system reacts depends on the program context. n If the types of the objects involved are defined VWDWLFDOO\, a V\QWD[HUURU occurs. ([DPSOH: '$7$GDWH7<3(G9$/8( WLPH7<3(W ),(/'6<0%2/6IVBGDWH!7<3(GIVBWLPH!7<3(W $66,*1GDWH72IVBGDWH!WLPH72IVBWLPH! IVBWLPH! IVBGDWH! n In the case of G\QDPLFtyping a UXQWLPHHUURU occurs, because the field symbols are not assigned types until the assignment of the data objects at runtime. ([DPSOH: ),(/'6<0%2/6IVBGDWH!7<3($1<IVBWLPH!7<3($1< (Rest as above) © SAP AG BC401 2-25 &RQYHUVLRQ8QGHU8QLFRGH &RQYHUVLRQEHWZHHQIODWVWUXFWXUHV À{'ÇÆBÈBÉIÊKC§ËÆBÈBÉIÊK¡ 8QGHUZKDWFRQGLWLRQ LVWKLVDVVLJQPHQW SRVVLEOH" 'HFLVLYHFULWHULRQ )UDJPHQWYLHZ O _ T J/U [ Ñ ÎÏÓÐ ÔÎ ÒÐÕÍÎ>uÐ ÔÎ#ÒÐ O _ T J/U ] Ñ Î ÒÐ Ñ ÎRu Ð Ñ Î>u Ð ÍCÎÏuÐ Ñ Î ÒÐ Ì Ö<ÎÏ×Ð Ì O _ T J/U [ O _ T J/U ] Ñ Î3wØ|Ð $VVLJQPHQWLVSRVVLEOH⇐ ÍCÎÏuÐ Ñ Î ÒÐ Ì Ö<ÎÏ×Ð &RQYHUVLRQEHWZHHQIODWVWUXFWXUHVLVSRVVLEOHLIWKHIUDJPHQWVRI WKHVRXUFHDQGWDUJHWVWUXFWXUHVPDWFKERWKLQW\SHDQGOHQJWKLQ WKHOHQJWKRIWKHVKRUWHUVWUXFWXUH SAP AG 2002 n For some data types there are, for technical reasons, specific alignment requirements that depend on the individual platforms. (In the memory, fields of this type must begin and end on specific addresses - for example, a memory address divisible by four.) n Within a structure, the runtime system, if necessary, inserts bytes before or after these components with alignment requirements to achieve the alignment needed. These bytes are known as $OLJQPHQW. n To check whether the conversion is even permitted, the system first creates the Unicode fragment view of the structures by grouping adjacent components and alignment gaps (one group each for character-type types [F, Q, G, W], byte-type types, and types L, I, and S). n Adjacent character-type components of a structure are therefore only grouped together if there are no alignment gaps between these components. Adjacent byte-type components are grouped in the same way. n If the fragments of the source and initial structures match the type and length in the length of the shorter structure, the conversion is allowed. n If the target structure is longer than the source structure, the character-type components of the remainder are filled with space characters. All other components in the remainder are filled with the type-specific initial value, alignment gaps are filled with null bytes. © SAP AG BC401 2-26 &RQYHUVLRQ8QGHU8QLFRGH &RQYHUVLRQEHWZHHQVWUXFWXUHVDQGVLQJOHILHOGV À{'Â¥C¬I­FB·BËÆÈ/É/ÊF¡ UÙBÚ*Û ÜCÝ M Ñ Î>v Ð 8QGHUZKDWFRQGLWLRQ LVWKLVDVVLJQPHQW SRVVLEOH" 'HFLVLYHFULWHULRQ )UDJPHQWYLHZ O _ TJ/U Ñ ÎÏÓÐ ÔBÎÏÒÐ ÍCÎÏuÐ Ñ Î ÒÐ UÙBÚ*Û ÜÝ M O _ *T J/U $VVLJQPHQWLVSRVVLEOH⇐ &RQYHUVLRQEHWZHHQVWUXFWXUHVDQGVLQJOHILHOGVLVSRVVLEOHLI WKHVWUXFWXUHEHJLQVZLWKDFKDUDFWHUW\SHIUDJPHQWDQGWKLV IUDJPHQWLVDWOHDVWDVORQJDVWKHVLQJOHILHOG SAP AG 2002 The following rules apply for the conversion of a structure to a single field and vice versa: If the single field is type F, but the structure isn’t completely character-type, the conversion is only allowed if the structure begins with a character-type group and this group is at least as long as the single field. The conversion then takes place between the first character-type group of the structure and the single field. If the structure is the target field, the character-type parts of the remainder are filled with space characters and all other components with the type-specific initial value. The conversion is not allowed if the structure is not purely character-type and the single field is not type F. Internal tables can be converted if their row type can be converted. © SAP AG BC401 2-27 ([DPSOHRI8VLQJWKH&RQYHUVLRQ5XOHV 3$5$0(7(56SBGDWH/,.(V\GDWXP '$7$%(*,12)VBGDWH \HDU 7<3(Q &KDUDFWHUW\SH PRQWK 7<3(Q VLQJOHILHOG GD\ 7<3(Q (1'2)VBGDWH 029(SBGDWH72VBGDWH VBGDWHGD\ 029(VBGDWH72SBGDWH l l Þ ÙMCß _ Ü &KDUDFWHUW\SH VWUXFWXUH O5ÙCMß _ Ü 6LQFHWKHVWUXFWXUHVBGDWHLVSXUHO\FKDUDFWHUW\SHLWLVWUHDWHGOLNH DW\SHFGDWDREMHFWGXULQJFRQYHUVLRQ 7KLVPHDQVLWLVWUDQVIHUUHGOHIWDOLJQHGFKDUDFWHUE\FKDUDFWHU SAP AG 2002 n VBGDWHis structured in such a way that the first four characters of a variable specify the year, the next two specify the month, and the last two the day. If a date is assigned to this structure using the 029( statement, the characters are then copied left-aligned. You can then determine the year, month, and day directly using the components of the structure, without having to use offsets. © SAP AG BC401 2-28 2IIVHWDQG/HQJWK$FFHVVHVDQG(OHPHQWDU\'DWD 2EMHFWV $FFHVVWRVLQJOHILHOGVVSHFLI\LQJRIIVHWDQGOHQJWK VWDWHPHQW!ILHOG!RII! OHQ! B à5F¬<­<eá/1  /âã ²<7äåI ª F¬<­ Zeá/1 ¤ ª§/â1°1±/ ²±{KæB°B£Ká³/¡ U5ÙBÚ*Û ÜÝ M ç{»¢I/Xà¥C¬/­KIè1!7 ª'¥C¬/­F/èK°-Ké¡ ê ÙBÚ*Û ÜÝ M {°C±'²¥±Fæ°I£á l l $%$3 )RUFKDUDFWHUW\SHILHOGVRIIVHWDQGOHQJWKDUHLQWHUSUHWHGFKDUDFWHU E\FKDUDFWHU ,QWKHFDVHRIE\WHW\SHILHOGVWKHYDOXHVIRURIIVHWDQGOHQJWKDUH WDNHQLQE\WHV SAP AG 2002 n n Offset/length accesses are permitted on character-type single fields, single fields with the type VWULQJ, and single fields of the types [ and [VWULQJ. For character-type fields and type VWULQJfields, offset and length are interpreted character by character. Only with types [ and[WULQJare the values for offset and length taken in bytes. © SAP AG BC401 2-29 2IIVHWDQG/HQJWK$FFHVVHVDQG6WUXFWXUHV $FFHVVLQJVWUXFWXUHVE\VSHFLI\LQJRIIVHWDQGOHQJWK VWDWHPHQW!VWUXFWXUH!RII! OHQ! B ë²C1¢5©K£ìK­IìÃF­CÉå ȬCÈI­íîF / ï É­´CÁ ì1­í!/îK®/ Æ'Ê1É/´CÁ ì1­í!/îK®/ ÁBðC­ / C¬CÈ'ñ¼¯KæC / ©K£ìK­IìCÃF­É¡ ò Ü ò IS ÜT Ñ Î>óØÐ Ñ ÎôweóР³ ³ ³ ˬ ³ Ñ Î3wØóÐ}Ì Ñ ÎÏz|Ð õ5ö fÏf Î i h'÷ Ð I»K£/» ÀµÊ{Æ ­<1´FÁ ì1­¹1ºC¢5©1®ìK­IìCÃF­CÉèCî *°FæCé¡ 6WUXFWXUHPXVWVWDUWZLWKDFKDUDFWHUW\SHIUDJPHQW l $FFHVVLVRQO\DOORZHGZLWKLQWKHFKDUDFWHUW\SHLQLWLDOSDUW l 2IIVHWDQGOHQJWKVSHFLILFDWLRQVDUHLQWHUSUHWHGDVFKDUDFWHUV l SAP AG 2002 n Offset and length accesses to structures are only permitted in Unicode programs if the structure is flat and the offset and length specifications only contain character-type fields from the beginning of the structure. This means, the access will cause an error if the offset and length area contains both character-type and non-character-type components. n If an offset/length access is allowed in a Unicode program, both offset and length specifications are interpreted as characters. n 5HFRPPHQGDWLRQ Only use offset and length accesses if it is necessary or useful. Bear in mind that processing component by component and using character string operations is generally safer and more readable. © SAP AG BC401 2-30 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO6XPPDU\ <RXDUHQRZDEOHWR l 8VHHOHPHQWDU\GDWDREMHFWVDQGVWUXFWXUHV DSSURSULDWHO\ l 8VHQXPHULFGDWDW\SHVDSSURSULDWHO\ l 8VHDXWRPDWLFW\SHFRQYHUVLRQVDSSURSULDWHO\ l 7DNHWKHVSHFLDOIHDWXUHVRIFKDUDFWHUVWULQJ SURFHVVLQJLQ8QLFRGHLQWRDFFRXQW SAP AG 2002 © SAP AG BC401 2-31 ([HUFLVH 8QLW 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO 7RSLF 'HILQLQJ'DWD7\SHVDQG'DWD2EMHFWV %DVLF6WDWHPHQWV 3URFHVVLQJ&KDUDFWHU6WULQJV At the conclusion of these exercises, you will be able to: • Define structure types locally in the program • Define elementary and complex data objects • Split strings • Use conversion rules • Display the contents of data objects in lists In this exercise, you will use a template to create a program that receives a single data record from the database table SFLIGHT in form of a character string. The program will split the this character string into its components and display it formatted in a list. Because the focus of this exercise is not on the transfer of data as a character string, we will use a function module that will provide us with the required database. This will simulate actual cases, such as data transfer from an external system. 3URJUDP 7HPSODWH 0RGHOVROXWLRQ =%&BB63/,7B675,1* 6$3%&B'727B63/,7B675,1* 6$3%&B'726B63/,7B675,1* LV\RXUWZRGLJLWJURXSQXPEHU 1-1 Copy the program, 6$3%&B'727B63/,7B675,1* and give it the new name =%&BB63/,7B675,1*. 1-2 Familiarize yourself with the main body of the program. Pay special attention to the content of the data object datastring after the function module call. Use the Debugger to do this, and/or display the character string in a list. (The function module itself is here seen as a black box. For this exercise, it is not necessary to understand its construction.) 1-3 To be able to split the character string into its components you must first remove the ## characters. Remove the two leading separators from the character string first. Then copy the initial part up to the closing separators to the auxiliary variable set_string. For this, set_string has to be defined appropriately. © SAP AG BC401 2-32 1-4 Now use the separators to split the contents of the auxiliary variable set_string into the structure wa_flight_c. The latter is typed with the local program structure type st_flight_c. You still have to comment out the components of this structure type and assign them an appropriate type. 1-5 As a test, display the fields of the structure, wa_flight_c in a list. 1-6 In the list displayed in exercise 1-5, you should have observed that some of the fields were displayed without formatting – for example, the PRICE field. Your next step is to change this. To do this, convert the data you have extracted by copying it to data objects with suitable types. Also, not all components of wa_flight_c are to be displayed. For this purpose, a structure wa_flight has already been defined. It is typed with the structure type st_flight. You must comment out the components of st_flight and find appropriate types for these components for the formatting. Then copy the identically-named components of the character-type structure wa_flight_c to the fields of the structure wa_flight. Display the contents of the structure wa_flight in a list. Use the appropriate formatting options for the WRITE statement for the fldate and price components. © SAP AG BC401 2-33 6ROXWLRQ 8QLW 'DWD7\SHVDQG'DWD2EMHFWVLQ'HWDLO 7RSLF 'HILQLQJ'DWD7\SHVDQG'DWD2EMHFWV %DVLF6WDWHPHQWV 3URFHVVLQJ&KDUDFWHU6WULQJV REPORT sapbc401_dtos_split_string. TYPES: BEGIN OF st_flight_c, mandt(3) TYPE c, carrid(3) TYPE F, TYPE Q, connid(4) TYPE Q, fldate(8) TYPE F, price(20) TYPE F, currency(5) TYPE F, planetype(10) TYPE Q, seatsmax(10) TYPE Q, seatsocc(10) paymentsum(22) TYPE F, seatsmax_b(10) TYPE Q, seatsocc_b(10) TYPE Q, seatsmax_f(10) TYPE Q, seatsocc_f(10) TYPE Q, END OF st_flight_c, BEGIN OF st_flight, carrid(3) TYPE c, connid(4) TYPE n, fldate TYPE G, price(9) currency(5) TYPE S'(&,0$/6, TYPE F, planetype(10) TYPE F, seatsmax seatsocc TYPE L, TYPE L, END OF st_flight. © SAP AG BC401 2-34 DATA: datastring TYPE string, VHWBVWULQJ7<3(VWULQJ wa_flight_c TYPE st_flight_c, wa_flight TYPE st_flight. START-OF-SELECTION. CALL FUNCTION ’BC401_GET_SEP_STRING’ * EXPORTING * IM_NUMBER = ’1’ * IM_TABLE_NAME = ’SFLIGHT’ * IM_SEPARATOR = ’#’ * IM_UNIQUE = ’X’ IMPORTING ex_string = datastring EXCEPTIONS no_data = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF. 6+,)7GDWDVWULQJ%<3/$&(6 ),1' ,1GDWDVWULQJ ,)V\VXEUF! 0(66$*(D EF (1',) 63/,7GDWDVWULQJ$7 ,172VHWBVWULQJGDWDVWULQJ 63/,7VHWBVWULQJ$7 ,172 ZDBIOLJKWBFPDQGW ZDBIOLJKWBFFDUULG ZDBIOLJKWBFFRQQLG ZDBIOLJKWBFIOGDWH ZDBIOLJKWBFSULFH ZDBIOLJKWBFFXUUHQF\ ZDBIOLJKWBFSODQHW\SH © SAP AG BC401 2-35 ZDBIOLJKWBFVHDWVPD[ ZDBIOLJKWBFVHDWVRFF ZDBIOLJKWBFSD\PHQWVXP ZDBIOLJKWBFVHDWVPD[BE ZDBIOLJKWBFVHDWVRFFBE ZDBIOLJKWBFVHDWVPD[BI ZDBIOLJKWBFVHDWVRFFBI 029(&255(6321',1*ZDBIOLJKWBF72ZDBIOLJKW WRITE: / wa_flight-carrid, wa_flight-connid, ZDBIOLJKWIOGDWH''00<<<< ZDBIOLJKWSULFH&855(1&<ZDBIOLJKWFXUUHQF\ ZDBIOLJKWFXUUHQF\ ZDBIOLJKWSODQHW\SH ZDBIOLJKWVHDWVPD[ ZDBIOLJKWVHDWVRFF © SAP AG BC401 2-36 8VLQJ,QWHUQDO7DEOHV &RQWHQWV l ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV l 'HILQLQJLQWHUQDOWDEOHV l ,QWHUQDOWDEOHRSHUDWLRQV l 1RWHVRQSHUIRUPDQFH l 6SHFLDOLQWHUQDOWDEOHV SAP AG 2002 © SAP AG BC401 3-1 8VLQJ,QWHUQDO7DEOHV8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 'HILQHLQWHUQDOWDEOHV l 3HUIRUPRSHUDWLRQVRQLQWHUQDOWDEOHV l ,GHQWLI\WDEOHNLQGVDQGXVHWKHPDSSURSULDWHO\LQ GLIIHUHQWVLWXDWLRQV SAP AG 2002 © SAP AG BC401 3-2 8VLQJ,QWHUQDO7DEOHV,QWHJUDWLRQLQ&RXUVH &RQWHQW !#"! %$'&)(*+ , ,- ./021 3246587 4 1 27 9 4: SAP AG 2002 © SAP AG BC401 3-3 8VLQJ,QWHUQDO7DEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV 'HILQLWLRQ 'HILQLWLRQ 2SHUDWLRQV 2SHUDWLRQV 6SHFLDOVLWXDWLRQV 6SHFLDOVLWXDWLRQV 1RWHVRQSHUIRUPDQFH 1RWHVRQSHUIRUPDQFH SAP AG 2002 © SAP AG BC401 3-4 7KH,QWHUQDO7DEOHD'DWD2EMHFWRI9DULDEOH/HQJWK (OHPHQWDU\GDWDREMHFWV 6WUXFWXUHV $%$3 SURJUDP 6WDWLFGDWDREMHFWV H[FHSWIRU W\SHV675,1*;675,1* ,QWHUQDOWDEOH $WUXQWLPHWKHUXQWLPHV\VWHPDOORFDWHV PHPRU\IRUWKHOLQHVLQWKHWDEOHDVQHHGHG G\QDPLFWDEOHH[WHQVLRQ SAP AG 2002 n Internal tables are data objects that allow you to store datasets with a fixed structure in memory. The data is stored line by line in memory. Each line has the same structure. n You can also refer to each component in a line as a column in the internal table. You refer to each line in the internal table as a table line or table entry. n Internal tables are G\QDPLFGDWDREMHFWV - that is, they can hold any number of lines of a fixed type. The number of lines in an internal table is limited only by the capacity of the specific system with which you are working. n You can define the line type of an internal table to include elementary, structured, or even table types, and can be as complex as you want to make it. © SAP AG BC401 3-5 $WWULEXWHVRI,QWHUQDO7DEOHV /LQHW\SH &$55,' &211,' ',67$1&( ',67,' /LQH LQGH[ $$ 0, /+ .0 /+ 4) 64 8$ .0 0, 0, 0, 64 ,QGH[DFFHVV .H\DFFHVV 7DEOHNLQG Standard table Sorted table Hashed table .H\GHILQLWLRQ ( .H\ILHOGV ( 6HTXHQFH ( 8QLTXHQHVV SAP AG 2002 n Each internal table has the following attributes: é /LQHW\SH You use the line type to specify which columns are to be included in your internal table. You must assign a name and type to each column. You generally define a line type using a structure type. é .H\ Internal tables have a key, just like database tables. The key is defined by: Specifying the FROXPQV that should belong to the NH\; the VHTXHQFH; and whether or not the key should be XQLTXH or QRQ XQLTXH. Depending on how you define your internal table, the runtime system may create an DGGLWLRQDO XQLTXHNH\(the LQGH[) for some internal tables (this will be discussed in more detail later). For simplicity’s sake you can think of the index as a OLQHQXPEHU. é 7DEOHNLQG There are three table kinds in ABAP. Each kind has different attributes, which specify whether the key is unique, how the index is managed, and how the table data is addressed internally. The table kind specifies the possible accesses. The purpose of this is to provide particular support for special access types from the runtime system (will be discussed later). © SAP AG BC401 3-6 /LQN%HWZHHQ7DEOH.LQGDQG$FFHVV7\SH ,QGH[WDEOHV 7DEOHNLQG STANDARD TABLE +DVKHGWDEOH SORTED TABLE HASHED TABLE ,QGH[DFFHVV Q .H\DFFHVV f% g%6h j g6k Y [ g6%k X TUM^ iU%l g W ^> QTi [ mN =g T %l op n [i'8V Y SB[ 8QLTXHQHVV ;=<>;@?BAC;ED FGA@H AE;ED FIAJHLKM;N<I;O?PAE;CD FIACH AJ;@D FQAEH $FFHVVE\ R>SUTMV W XZY\[]6^8_ R`S6T'V W Xba^8X c=^8XdSe[%W X SAP AG 2002 The table kind is linked to the access type as follows: n You can only perform an index access (the fastest type of access) on STANDARD and SORTED tables. n The runtime system implements key accesses of SORTED and HASHED tables in a way that optimizes runtime performance. Key access of STANDARD tables is by WDEOHVFDQ - that is, comparing the field contents with the search key line by line, in a loop. n The runtime system implements key accesses of SORTED tables, for fully or partly qualified keys (left-aligned, no gaps, all fields filled with an "=") in a special way to optimize runtime. The same applies to partial sequential loops, where the loop condition is specified using the key fields. With the runtime-optimizing access, the runtime system keeps SORTED tables sorted by key fields, In all other cases, the system performs a WDEOHVFDQ. n The runtime optimizes key accesses of HASHED tables IRUIXOO\TXDOLILHGNH\VRQO\. The table entries are addressed by means of a special hash algorithm. This minimizes access time for reading single records with fully qualified keys. The access time is thus independent of the number of lines in the table. In all other cases, the system performs a WDEOHVFDQ. This means that you should only use HASHED tables if you want to access table entries using a fully-qualified key. © SAP AG BC401 3-7 8VLQJ,QWHUQDO7DEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV 'HILQLWLRQ 'HILQLWLRQ 2SHUDWLRQV 2SHUDWLRQV 6SHFLDOVLWXDWLRQV 6SHFLDOVLWXDWLRQV 1RWHVRQSHUIRUPDQFH 1RWHVRQSHUIRUPDQFH SAP AG 2002 © SAP AG BC401 3-8 2YHUYLHZ7\SHVRI'HILQLWLRQVIRU,QWHUQDO7DEOHV :LWKORFDOWDEOHW\SH ,PSOLFLWWDEOHW\SH /RFDOWDEOHW\SH *OREDOWDEOHW\SH 7<3(6 ORFDOBW\SH ORFDOBW\SH JOREDOBW\SH 7DEOH DWWULEXWHV ,QWHUQDOWDEOH '$7$ WBOLVW7<3( ORFDOBW\SH ORFDOBW\SH :LWKJOREDOWDEOHW\SH 7DEOH DWWULEXWHV ,QWHUQDOWDEOH '$7$ WBOLVW7<3( 7DEOH DWWULEXWHV ,QWHUQDOWDEOH '$7$ WBOLVW7<3( JOREDOBW\SH JOREDOBW\SH SAP AG 2002 n There are several ways to define an internal table in ABAP: é Use the TYPES statement to define a table type. Then use this to assign a type to one or more data objects or interface variables. é Alternatively, declare the table attributes directly when you define the data object (that is, use a ERXQG type). é The third option is to define an internal table using a global table type (defined in the ABAP Dictionary). n The tables you define using the first or second option are visible only in the program in which you define them. Whenever you need table type visible from all programs, create a global table type (that is, use the third option). © SAP AG BC401 3-9 7KH'DWD7\SHRIDQ,QWHUQDO7DEOH /RFDOWDEOHW\SHLQWHUQDOWDEOH 7<3(6 RU $WWULEXWHV '$7$ QDPH7<3(WDEOHBW\SH 7<3( WDEOHBNLQG ( 7DEOHNLQG :,7+NH\BGHI :,7+ NH\BGHI NH\BGHI ( .H\ 2)OLQHBW\SH 2) ( /LQHW\SH FROXPQV >,1,7,$/6,=(Q@ ,1,7,$/6,=( ( ,QLWLDOVL]H RSWLRQDO *OREDOWDEOHW\SH $WWULEXWHV JOREDOBW\SH ( 7DEOHNLQG ,QSXWRQVFUHHQXVHG WRVSHFLI\DWWULEXWHV ( /LQHW\SH FROXPQV ( .H\ SAP AG 2002 n To define a table type (explicitly or implicitly), you must give the type (or data object) a name, as well as specifying a WDEOHNLQG OLQHW\SH and NH\ n If you are defining a local table type, enter the kind after TYPE and the line type after OF. You must list the key fields after WITH. n You create and edit global types in the ABAP Dictionary. If you are defining a global table type, specify the same information on the maintenance screens. n For table types defined in a program, you can enter the number of lines that the runtime system should reserve when it initializes the data object, after the INITIAL SIZE addition. This makes sense if you know exactly how many lines you will want in your table when you create it. However, if your table needs more lines at runtime, it will not be limited in size by this addition, since the runtime system frees the necessary memory dynamically. (Internal tables are G\QDPLF data objects). © SAP AG BC401 3-10 7DEOH$WWULEXWH/LQH7\SH /LQHW\SH /RFDOVWUXFWXUHW\SH *OREDOVWUXFWXUHW\SH 7<3(6 7<3(6 OLQHBW\SH %(*,12)OLQHBW\SH (1'2)OLQHBW\SH OLQHBW\SH /RFDOVWUXFWXUH '$7$ '$7$ VWUXFWXUH VWUXFWXUH7<3( 7DEOHW\SH QDPH7<3(WDEOHBNLQG 7<3( QDPH/,.(WDEOHBNLQG /,.( :,7+NH\BGHI :,7+NH\BGHI 2)VWUXFWXUH VWUXFWXUH 2) 2)OLQHBW\SH 2) OLQHBW\SH >,1,7,$/6,=(Q@ >,1,7,$/6,=(Q@ SAP AG 2002 n To specify the line type of an internal table, you can use all the local and global data types or data objects. n Internal tables are most frequently used to display contents of the database tables. Normally, nonnested structured data types are used for this. n n If you use a line type, you must use a statement in the form: 7<3( WDEOHBNLQG 2) line_type, where WDEOHBNLQG is the kind of table (to be discussed later) and line_type is the name of the structure type you are using. If you use structure (data object), you must use a statement in the form: /,.( WDEOHBNLQG 2) line_type, where structure is the name of the structure object you are using. © SAP AG BC401 3-11 7DEOH$WWULEXWH7DEOH.LQGDQG.H\ 7<3(6 WDEOHBNLQG LWDEW\SH7<3(WDEOHBNLQG 2)OLQHBW\SH :,7+ NH\B NH\BGHI :,7+NH\BGHI >,1,7,$/6,=(Q@ '$7$ WBQDPH7<3(LWDEW\SH WDEOHBNLQG 67$1'$5'7$%/( 6257('7$%/( +$6+('7$%/( NH\B NH\BGHI >12181,48(@^.(<FROFROQ_ '()$8/7.(<` ^81,48(_12181,48(`.(<FROFROQ 81,48(.(<FROFROQ SAP AG 2002 n There are three parameters that you use to specify a table kind for your internal table: STANDARD TABLE, SORTED TABLE and HASHED TABLE n You specify the table key with the :,7+ NH\BGHI addition. NH\BGHI includes the names of all the key fields in order and specifies whether the key is to be UNIQUE or NON-UNIQUE. n The combination of the table kind and the key definition is very significant, because of the special support that certain table kinds receive with specific types of read access. You can use any of the following combinations: é For STANDARD tables: Either create a user-defined key by naming the key fields after NON-UNIQUE KEY, or specify the standard key using the WITH DEFAULT KEY addition. The standard key consists of all the fields with character-type data types (c, n, d, t, x, string, xstring). é For SORTED tables: List the key fields after WITH UNIQUE KEY or NON-UNIQUE KEY as appropriate. é For HASHED tables: List the key fields after WITH UNIQUE KEY. n Alternatively, use the pseudo-component table_line, if you are specifying a table without a structured line type, or if the entire table line is being used as the key. This will be discussed in more detail later in the unit. © SAP AG BC401 3-12 ([DPSOH6WDQGDUG7DEOHZLWK/RFDO7\SH /LQHW\SH 7<3(6 VBGLVWDQFHBW\ %(*,12)VBGLVWDQFHBW\ FDUULG7<3(VBFDUUBLG FRQQLG7<3(VBFRQQBLG GLVWDQFH7<3(VBGLVWDQFH GLVWLG7<3(VBGLVWLG (1'2)VBGLVWDQFHBW\ 7DEOHW\SH 7<3(6 WWBGLVWDQFHBW\ WWBGLVWDQFHBW\7<3(67$1'$5'7$%/( 2)VBGLVWDQFHBW\ VBGLVWDQFHBW\ :,7+12181,48( .(<GLVWDQFHGLVWLG ,QWHUQDOWDEOH '$7$ WWBGLVWDQFHB W\ WWBGLVWDQFH7<3(WWBGLVWDQFHBW\ WWBGLVWDQFHBW\ WWBGLVWDQFH WWBGLVWDQFH ,QWHUQDOWDEOH RIWKHWDEOHNLQG 67$1'$5'7$%/( SAP AG 2002 n The above example shows the definition of an internal table (tt_distance) using a local table type (tt_distance_ty), which itself uses a local line type (s_distance_ty). n The internal table defined here is a STANDARD table with the line type s_distance_ty. It contains the columns carrid, connid, distance and distid. n The distance and distid fields are key fields. The key is not unique. © SAP AG BC401 3-13 ([DPSOH6RUWHGDQG+DVKHG7DEOH 6HTXHQFH 6RUWHGWDEOH '$7$ GLVWDQFHBUDQF GLVWDQFHBUDQF 7<3(6257('7$%/( VBGLVWDQFHBW\ 2)VBGLVWDQFHBW\ :,7+12181,48(.(< GLVWLGGLVWDQFH 6HTXHQFH FDUULG FRQQLG /+ /+ $$ 40 6HTXHQFH +DVKHGWDEOH FDUULG '$7$ GLVWDQFHBEXIIHU GLVWDQFHBEXIIHU 7<3(+$6+('7$%/( VBGLVWDQFHBW\ 2)VBGLVWDQFHBW\ :,7+81,48(.(< FDUULGFRQQLG /+ $$ 40 /+ FRQQLG GLVWDQFH GLVWLG .0 .0 0, 0, GLVWDQFH GLVWLG .0 0, 0, .0 SAP AG 2002 n The above example shows the definition of a SORTED table and a HASHED table. Both tables have the same line type as the STANDARD table on the previous slide. n Note that the contents of the table are in a different order. For SORTED tables, the sequence of the entries in the internal table is determined by the sequence of fields in the key definition. © SAP AG BC401 3-14 7KH6WDQGDUG7DEOH7\SH '$7$ 7<3( 7$%/( WBQDPH7<3(7$%/( 2) 2)OLQHBW\SH ,QWHUSUHWHGE\ WKHV\VWHPDV 'HILQLWLRQE\ VWDQGDUGWDEOHW\SH '$7$ 7<3( 67$1'$5' 7$%/( WBQDPH7<3(67$1'$5'7$%/( 2) 2)OLQHBW\SH :,7+'()$8/7.(< :,7+'()$8/7.(< ([DPSOH '$7$ 7<3(7$%/(2) WBVIOLJKW7<3(7$%/(2)VIOLJKW SAP AG 2002 n A standard type exists for defining standard tables with bound types. (Table type STANDARD TABLE, key WITH DEFAULT KEY). When you create such a table, you can omit the STANDARD and WITH DEFAULT KEY additions, since the runtime system supplies them automatically. n Note however, that the standard table type exists for data objects only. If you are defining a table type that you want to use to provide a type for data objects, you must specify all its attributes completely. n Incomplete table types are known as JHQHULF. You can only use them to assign types to table-type interface parameters. © SAP AG BC401 3-15 ,QWHUQDO7DEOHVZLWKDQ8QVWUXFWXUHG/LQH7\SH 'HILQLWLRQ '$7$ LWBILHOGV7<3(67$1'$5'7$%/(2)GGOILHOGQDPH WDEOHB :,7+.(<WDEOHBOLQH WDEOHBOLQH ZDBILHOG7<3(GGOILHOGQDPH 6(/(&7ILHOGQDPH)520GGOWDEOHRIWUDQVSWDEOHV )LOO ,1727$%/(LWBILHOGV :+(5(WDEQDPH 63)/, .H\ DFFHVV 5($'7$%/(LWBILHOGV,172ZDBILHOG WDEOHB :,7+.(<WDEOHBOLQH WDEOHBOLQH &,7<)520 SAP AG 2002 n Use an unstructured line type if you need a single-column internal table. The slide shows an example of a single-column table with the line type field_name. n To declare an explicit key, you must use the pseudo-component table_line. n You can use internal tables with an unstructured line type in the following ABAP statement (among others): é SET PF-STATUS .. EXCLUDING itab. (deactivate function codes dynamically) é SPLIT .. INTO TABLE itab. (split a string dynamically) n You can use a key access, for example, to ascertain whether a specific entry H[LVWV. © SAP AG BC401 3-16 8VLQJ,QWHUQDO7DEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV 'HILQLWLRQ 'HILQLWLRQ 2SHUDWLRQV 2SHUDWLRQV 6SHFLDOVLWXDWLRQV 6SHFLDOVLWXDWLRQV 1RWHVRQSHUIRUPDQFH 1RWHVRQSHUIRUPDQFH SAP AG 2002 © SAP AG BC401 3-17 2YHUYLHZ7\SHVRI2SHUDWLRQ ,QWHUQDOWDEOH DVDGDWDREMHFW 2SHUDWLRQVRQRQHRU PRUHOLQHV (GLWLQJOLQHV LQDORRS RU ( &RS\ 029( &/($5 .HHSPHPRU\DYDLODEOH ( ,QLWLDOL]H )5(( 5HOHDVHPHPRU\ ( ,QLWLDOL]H ( &RPSDUHXVLQJRSHUDWRUV !! ! ( 6RUW 6257 ( ,QVHUW ( 5HDG ( &KDQJH ( 'HOHWH ,16(57 5($' 02',)< '(/(7( ( ,QVHUWVXPPDWHG ( (GLWOLQHV VHTXHQWLDOO\ /223 FRPPDQGEORFN (1'/223 &2//(&7 ( $UUD\)HWFK 6(/(&7 ,1727$%/( SAP AG 2002 You can perform three different types of operations on internal tables: n 2SHUDWLRQVRQWKHZKROHGDWDREMHFW: Elementary operations available include MOVE (copy the content line by line), CLEAR (delete the content, but keep the memory allocated), and FREE (delete the content and release the memory). You can also use all the numerical comparison operators with internal tables in logical expressions. With these operators, the number of lines is compared first and then, if necessary, the line contents. (This is recursive for deep types). For more information, refer to the documentation on internal tables. You can use the SORT statement to sort the content of STANDARD and HASHED tables. This statement allows you to sort the table by one or columns, specifying DVFHQGLQJ or GHVFHQGLQJ for each column. For more details, refer to the keyword documentation for the SORTstatement. You can use the SELECT ... INTO TABLE statement to copy the contents of database tables directly into internal tables. n 2SHUDWLRQVRQOLQHV: You can use the INSERT, READ, MODIFY, DELETE, and COLLECT statements to perform operations on one or more lines in the internal table. The syntax of the first four of these statements is dealt with in the slides that follow. For the syntax of the COLLECT statement, refer to the online documentation. n /RRSSURFHVVLQJ You can use the LOOP AT ... ENDLOOP statement to process the lines of the internal table sequentially. The exact syntax for this is dealt with in the slides that follow. © SAP AG BC401 3-18 /LPLWLQJWKH6FRSHRI/LQH2SHUDWLRQV7DUJHW 5HFRUGVDQG$FFHVV7\SH 6SHFLI\VHWRIWDUJHWUHFRUGV 7DEOHNH\ /LQHLQGH[ IRULQGH[WDEOHV Q FRQGLWLRQ! &RQGLWLRQDSSOLHGWRDQ\QXPEHURIFROXPQV >QQ@ ,QGH[LQWHUYDO IRULQGH[WDEOHV 6SHFLI\DFFHVVW\SHGDWDWUDQVIHUW\SH :RUNDUHD &RS\LQJSURFHVV 7DEOH )LHOGV\PERO 'LUHFWDFFHVVE\ GHUHIHUHQFHGSRLQWHU GHUHIHUHQFHGSRLQWHU ,QVHUW XVLQJWDEOH SAP AG 2002 n Almost all line operations and loop processing statements offer you several options for specifying the target set of records to be processed. You can specify these target records by declaring a key or index, by formulating a condition that applies to some of the columns, or by specifying an index interval. Your use of these options is limited only by the table kind you have chosen. Example: You cannot specify a line in a hashed table using an index. n When accessing table rows, you have two possibilities for a number of line operations and for loop processing: You can either copy the data into a structure with the same type as the line type of the internal table, or you can set a pointer to a table line and access the data in that line directly. n In particular, when you insert table lines, you can pass the data to be inserted using another internal table. n Note that all statements either set a return value or trigger a runtime error. If a return code has been set, it is stored in the sy-subrc field after the statement has been executed. Runtime errors are only triggered if the data passed at runtime are crucial in determining whether or not the operation can be performed. Example: You try to insert a new line into a SORTED table using an index. If you insert the new line in exactly the right place in a sorted table, the system performs the operation. If not, the system returns a runtime error. © SAP AG BC401 3-19 3UHYLHZ)LHOG6\PER,V 'DWDREMHFWVLQWKH$%$3SURJUDP 'HILQLQJDILHOGV\PERO '$7$YDUBD7<3(L9$/8( ),(/'6<0%2/6IV!7<3(L ),(/'6<0%2/6 $VVLJQLQJDGDWDREMHFWWRD ILHOGV\PERO IV! YDUBD IV! $66,*1YDUBD72IV! $66,*1 72 YDUBD $VVLJQLQJDYDOXHWRDGDWDREMHFW XVLQJDILHOGV\PERO IV! IV! YDUBD 7LPH SAP AG 2002 n You can create a pointer to a data object in ABAP using a field symbol. n First, declare a data object using the ),(/'6<0%2/6 statement. This data object can contain a pointer to another data object at runtime. Where possible, you should give the field symbol the same type as the data object (7<3(L, in this example). n Note that the angle brackets (<>) are part of the name of the field symbol: In this example, the name is <fs>. n To point a field symbol at a data object, you must assign it to the object GDWDBREMHFW using the $66,*1GDWDBREMHFW72IV! statement. n You can use the field symbol to access the content of the data object to which it points - either to read or to change this content. n You can "redirect" a field symbol to a different data object at runtime using the $66,*1 statement. © SAP AG BC401 3-20 3UHYLHZ)LHOG6\PER,V 'HILQLQJWKHILHOGV\PERO '$7$LWBVIOLJKW7<3(7$%/(2) VIOLJKW ),(/'6<0%2/6IV!7<3(VIOLJKW $VVLJQLQJDOLQHWRWKHILHOGV\PERO qNg g h r j k kzgU{ V S ^ i8VsTtY*[IV2lM^`u uIvxw S%y IV! LWBVIOLJKW IV! WREHFRQWLQXHG LWBVIOLJKW $FFHVVLQJWKHOLQHFRQWHQWXVLQJWKHILHOGV\PERO :5,7(IV!FRQQLG IV!FDUULG /+ IV! LWBVIOLJKW SAP AG 2002 n In the above example, a field symbol is assigned the line type of an internal table. This makes it possible to assign a table line to this field symbol. The syntax required for this is discussed later in this unit. n After a field symbol has been assigned a line, it is also possible to access the individual column values of the assigned line. n As well as being able to read the data contents, you can also change the contents of the individual components. © SAP AG BC401 3-21 ,QVHUW .H\IURPZD VSHFLILHVWKHOLQH LWDE ZD ILOOZRUNDUHDZD ,16(57ZD,1727$%/(LWDE ,16(57 ,1727$%/( LWDE ZD Q LWDE >Q@ >Q@ ILOOZRUNDUHDZD Q ,16(57ZD,172LWDE,1'(;Q ,16(57 ,172 ,1'(; ,16(57/,1(62)LWDE ,16(57/,1(62) LWDE Q >)520Q72Q@ WDUJHW 2QO\LILWDELV DQLQGH[WDEOH WDUJHW Q SAP AG 2002 ,1727$%/(LWDE ,1727$%/( ,172 ,172LWDE>,1'(;Q@ To insert lines into a table, use the INSERT statement: n Using INSERT wa INTO TABLE itab, you insert the line whose data are stored in wa into the internal table. The record is inserted with reference to the table key. In STANDARD tables, the new line is appended to the end of the table. n Using INSERT wa INTO itab INDEX n, you insert the data from ZD into the internal table at the line with the index Q. If Q is an index value within the internal table, the lines with the index value greater than or equal to Q are pushed downwards. If n-1 is greater than the number of lines in the internal table, the line is not inserted. n Always add new lines to a SORTED table using the key. If you try to insert a line into a SORTED table using the index, you will not succeed unless the line has exactly the same index number as it would have when correctly sorted. Otherwise, a runtime error occurs. n Use INSERT LINES OF itab1 INTO TABLE itab2 to insert the lines of the internal table itab1 into the internal table itab2. Also, if itab1 is an index table, you can limit the number of lines to be inserted using an index interval (FROM n1 TO n2). n If your target table is an index table, you can use INSERT LINES OF itab1 INTO itab2 to insert the lines of the internal table itab1 into the internal table itab2. You can then specify the line index from which the lines are to be inserted using INDEX n. Also, if itab1 is an index table, you can limit the number of lines to be inserted using an index interval (FROM n1 TO n2). © SAP AG BC401 3-22 5HDGLQJD6LQJOH5HFRUGLQWRD:RUN$UHD8VLQJ WKH/LQH1XPEHU ZD LWDE Q ,QGH[ Q 5($'7$%/(LWDE,1'(;Q,172ZD>RSWLRQV@ 5($'7$%/( ,1'(; ,172 >RSWLRQV@ &203$5,1*FRPSBOLVW &203$5,1* 75$163257,1*WUDQVBOLVW 75$163257,1* FRPSBOLVW %HOLHELJH)HOGOLVWH $Q\ILHOGOLVW ( IIP ( $//),(/'6 WUDQVBOLVW ( IIN ( 12),(/'6 SAP AG 2002 n You can read single table lines from index tables using the READ TABLE itab INDEX n INTO wa statement. After INDEX, enter the index of the line you want to read. If the system was able to read the line, it sets the return code to sy-subrc = 0 and stores the data from the line in wa. The total number of lines is then in sy-tfill, the length of the lines in sy-tleng. If the system could not read the line, the return code sy-subrc is unequal to 0. In this case, the content of wa is not changed. n Use the option TRANSPORTING addition to specify the columns for which you want to transport data: é If you do not want to read any data, but simply want to ascertain whether or not line n exists (evaluating the return value sy-subrc), use the TRANSPORTING NO FIELDS addition. é If you want to read some of the columns in the line only, specify them after TRANSPORTING. Separate each column name with a space. n You can use the optional addition COMPARING I ... IP to ascertain whether or not the line to be read Q has specific column contents: To do this, copy the value of all columns that point to the records you want to read, into wa and list the columns after the COMPARING addition to the READ statement. If the system was able to read the line and if all the columns listed contain the values stored in ZD, it sets the return code sy-subrc to zero. If the system was able to read the line, but if one or more of the columns does not contain the value stored for it in ZD, it sets the return code sysubrc to two. If it could not read the line, it sets the return code to greater than two. n The COMPARING ALL FIELDS addition provides a shorter syntax for comparing all the columns. © SAP AG BC401 3-23 5HDGLQJD6LQJOH5HFRUGLQWRD:RUN$UHD8VLQJ WKH)LHOG&RQWHQWV .H\ ZD LWDE ZD 7DEOHNH\IURPZD ([SOLFLWWDEOHNH\ $Q\FRQWHQWIURPILHOGOLVW 5($'7$%/(LWDEVHDUFKBFODXVH,172ZD>RSWLRQV@ 5($'7$%/( ,172 $VLQLQGH[ DFFHVV VHDUFKBFODXVH )520ZD 7DEOHNH\ $Q\ILHOG FRQWHQWV :,7+7$%/(.(<N INQ IQ :,7+.(<FRO IFROP IP >%,1$5<6($5&+@ SAP AG 2002 n You can read individual lines from any kind of table using READ TABLE itab NH\ INTO wa. Use either a table key, or a comparison for some of the columns, as the search criterion NH\. n If you want to use a table key, you have two options: é Copy the key field values of the entry you want to read into the work area wa1 and use READ TABLE itab FROM wa1 INTO wa. Provided sy-subrc = 0, the system stores the result of the READ statement in the work area wa. Note that the values in wa1 that you have not explicitly filled contain appropriately-typed initial values. Thus, the READ TABLE itab FROM wa1 statement searches for a line that has initial values in the key fields that were not declared explicitly. Note: You can also use a single work area wa for both declaring the key fields and receiving the result: READ TABLE itab FROM wa INTO wa. é Evaluate the key fields explicitly using the call READ TABLE itab WITH TABLE KEY k1 = f1 ... kn = fn statement. In this case, you must fill all the key fields. n You can specify a formulated search condition to be applied to any columns using READ TABLE itab WITH KEY .... n However, you can only use dynamically formulated read accesses using the key and the READ TABLE itab FROM wa statement. © SAP AG BC401 3-24 5HDGLQJD6LQJOH5HFRUG8VLQJD)LHOG6\PERO IV! LWDE .H\ RU Q ,QGH[ ),(/'6<0%2/6IV!/,.(/,1(2)LWDE ,1'(;Q ,1'(; 5($'7$%/( 5($'7$%/(LWDE$66,*1,1*IV! $66,*1,1* ! NH\ Q ,QGH[ .H\ IV!ILHOGB :5,7()6!ILHOGB 6DPHDVZKHQUHDGLQJLQWRDZRUNDUHD SAP AG 2002 n You can use either a work area or a field symbol to access the individual lines in a table you want to read. n To use a field symbol, first define it using FIELD-SYMBOLS <fs>. Give it the same type as the line type of the internal table that you want to read. Example: FIELD-SYMBOLS <fs> LIKE LINE OF itab. n Set the pointer to the correct line using the ASSIGNING <fs> addition instead of INTO. You can use any search criterion you want. n You can access the components of the structure directly using the component names in the line type: é You can directly address elementary components in the line type using <fs>-field_1. é If the line type contains structured components (a structure or internal table), <fs>-component_name points to the entire structured component. To access the subcomponents of this structured component, you need another field symbol. n Note: If you are searching for a specific string in an internal table, you can also use the SEARCH statement. For more details, refer to the keyword documentation for the SEARCHstatement. © SAP AG BC401 3-25 &KDQJLQJWKH7DEOH8VLQJD:RUN$UHD .H\IURPZD VSHFLILHVWKHOLQH LWDE 02',)<7$%/( )520 02',)<7$%/(LWDE)520ZD ZD >75$163257,1*IIQ@ 75$163257,1* LWDE ZD ZD ILOOZRUNDUHDZD ILOOZRUNDUHDZD Q LWDE Q :+(5( ORJBH[SU 02',)< )520 02',)<LWDE)520ZD,1'(;Q ,1'(; 75$163257,1* >75$163257,1*IIQ@ 02',)<LWDE)520ZD 02',)< )520 75$163257,1* 75$163257,1*II :+(5(ORJBH[SU :+(5( SAP AG 2002 n The MODIFY TABLE itab FROM wa statement allows you to change the content of RQH line of the internal table itab. The runtime system specifies the line to be changed using the key values from the work area ZD and changes the non-key fields using the other fields. If your table has a nonunique key, the system changes the first entry only (using a linear search algorithm in STANDARD tables, and a binary search algorithm in SORTED tables). If you want to change only some of the fields (that is, columns) in a line, you must specify these after TRANSPORTING. n You can change the Qth line in an index table using MODIFY itab FROM wa INDEX n. Note that all the fields of the structure wa will be copied. Since changes to key fields in SORTED and HASHED tables can cause non-catchable runtime errors, you PXVW use the TRANSPORTING addition in this case. n If you want to make the same changes to several lines in a table, use the MODIFY itab FROM wa TRANSPORTING f1 f2 ... WHERE log_expr statement. Specify all the columns to be changed after TRANSPORTING. You must place the new values for these columns in the work area wa. Specify a condition for the line using the WHERE clause. © SAP AG BC401 3-26 &KDQJLQJD6LQJOH5HFRUG8VLQJD)LHOG6\PERO LWDE IV! .H\ RU IV!ILHOGB Q ,QGH[ ),(/'6<0%2/6IV!/,.(/,1(2)LWDE ,1'(;Q 5($'7$%/( 5($'7$%/(LWDE$66,*1,1*IV! $66,*1,1* NH\ )6!ILHOGB IV!ILHOGB IV!ILHOGB &DQQRWEHNH\ILHOGLQ VRUWHGRUKDVKHGWDEOHV Q ,QGH[ .H\ 6DPHDVZKHQUHDGLQJ LQWRDZRUNDUHD SAP AG 2002 n Instead of changing an individual line in a table using MODIFY, you can also change it using field symbols. First use READ TABLE ... ASSIGNING <fs> to assign a field symbol to the line to be changed. Then change the components directly using the field symbol components <fs>field_1 = .... n When you assign the field symbol using READ TABLE ... ASSIGNING you can specify the line to be read using a key (WITH TABLE KEY), index (for index tables), or a condition (WITH KEY). n Note that you cannot change key fields in SORTED or HASHED tables. - trying to do so causes a runtime error. © SAP AG BC401 3-27 'HOHWH ILOOZRUNDUHDZD 7DEOHNH\ LWDE '(/(7(7$%/( '(/(7(7$%/(LWDENH\ ZD NH\ ([SOLFLW ( )520ZD ( :,7+7$%/(.(< N INQ IQ LWDE Q Q :+(5( ORJBH[SU '(/(7(LWDE,1'(;Q '(/(7( ,1'(; 'HOHWHXVLQJDFRQGLWLRQ '(/(7(LWDE:+(5(ORJBH[SU '(/(7( :+(5( SAP AG 2002 n Use the READ TABLE itab INDEX n INTO wa statement to delete single table lines from index tables. Specify the line you want to delete using the table key. There are two ways of doing this: é Copy the key field values of the entry you want to delete into the work area wa and use DELETE TABLE itab FROM wa. é Fill the key fields directly in the DELETE statement using the WITH TABLE KEY k = f ... kQ = fQ addition. n You can delete the Qth line from the index table itab using DELETE itab INDEX n n If you want to deleteseveral lines from an internal table, use the DELETE itab WHERE log_expr statement. The condition that specifies the lines you want to delete is declared in ORJBH[SU, in the WHERE clause (where ORJBH[SU is any logical expression applied to the columns). © SAP AG BC401 3-28 /RRS3URFHVVLQJ UHVXOW ZD LWDE UHVXOW ( ,172ZD ( $66,*1,1*IV! IV! /223$7LWDEUHVXOW /223$7 >75$163257,1*12),(/'6@ ^>)520Q@>72Q@_ )520 72 >:+(5(ORJBH[SU@` :+(5( (1'/223 (1'/223 Q ,QGH[WDEOHVRQO\ ,QGH[WDEOH V\WDEL[FRQWDLQVOLQH LQGH[RIFXUUHQWOLQH SAP AG 2002 n Use the LOOP AT itab UHVXOW ... ENDLOOP statement to perform loop processing on the lines of the internal table itab. The system then executes the statement block between LOOP AT itab ... and ENDLOOP for each loop pass. UHVXOW stands for: é INTO wa: The system copies the table line it has processed in each loop pass into the work area wa é ASSIGNING <fs>: The relevant line is assigned to the field symbol <fs>. n With both variants you can use the TRANSPORTING NO FIELDS addition. No data is copied. Use this addition if, for example, you simply want to determine the number or indexes of the lines processed by the loop. n Specify the number of lines that the loop is to process using a WHERE clause (condition for any columns). n In an index table, limit the number of lines processed in the loop by declaring an index interval. n While the loop is being processed, the system field sy-tabix contains the index of the table row of the current loop pass. The total number of lines is in sy-tfill, the length of the lines in sytleng. n Note that in index tables, you can perform all the line operations (which you previously performed on the line specified in the INDEX n addition) ZLWKRXW this addition in the loop. The operation is then performed on the current line. © SAP AG BC401 3-29 2YHUYLHZRI2SHUDWLRQV |@}~'BU~M2}~'%) |OU#})'b}~'% C~UB'Z}\~'%\ 6257 D[]6^_ g i'i'^'T'T « k pS V TM^M p ^6[h i'^ i'S W g ] ^ Y SBW VP^M] ,16(57 5($'7$%/( 02',)< '(/(7( /223$7 c=^8X g i'i^MT'T e '' 8 8` M =¡'¡¢8£6¤I¥*¦G¢8£¤¦§ ¥¨'©ª ¢ ,16(57 5($'7$%/( 02',)< '(/(7( /223$7 SAP AG 2002 n Index accesses (such as APPEND, INSERT ... INDEX, LOOP AT ... FROM ... TO) are possible for standard and sorted tables. However, caution is advised when using INSERT or APPEND on sorted tables; this would violate the sort sequence and cause a runtime error. n You can use the SORT statement to sort standard and hashed tables. Sorted tables are sorted by the runtime system. n You can use key accesses with any table type, but their effect differs. A key access with INSERT has the same effect on standard tables as an APPEND, that is the relevant line is appended to the end of the table. In a sorted table however, the record is inserted in accordance with the sort sequence. In the case of a hashed table, the line is appended, but the system also changes the hash index internally. © SAP AG BC401 3-30 8VLQJ,QWHUQDO7DEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV 'HILQLWLRQ 'HILQLWLRQ 2SHUDWLRQV 2SHUDWLRQV 6SHFLDOVLWXDWLRQV 6SHFLDOVLWXDWLRQV 1RWHVRQSHUIRUPDQFH 1RWHVRQSHUIRUPDQFH SAP AG 2002 © SAP AG BC401 3-31 ,QWHUQDO7DEOHVZLWKD+HDGHU/LQH '$7$ 6\QWD[YDULDQW :RUNDUHD KHDGHU LWDE7<3(7$%/(2)VFDUU :,7+'()$8/7.(< 'DWDREMHFWLWDE :,7++($'(5/,1( :,7++($'(5/,1( LWDE '$7$ 6\QWD[YDULDQW REVROHWH LWDE LWDE7<3(VFDUU2&&856 2&&856 :,7++($'(5/,1( :,7++($'(5/,1( %RG\ '$7$ 6\QWD[YDULDQW REVROHWH %(*,12)LWDE2&&856 2&&856 %(*,12) FDUULG7<3(VBFDUUBLG XUO7<3(VBFDUUXUO (1'2) (1'2)LWDE SAP AG 2002 n As well as the internal tables we have discussed, you can define LQWHUQDOWDEOHVZLWKDKHDGHU. These consist of a pair of components - the internal table itself (the ERG\) and the work area (KHDGHU), with the same line type. The header and the body have the same name, which sometimes simplifies the syntax for table accesses. n There are several possible syntax variants used to define internal tables with header lines, some of which are shown in the slide. n Internal tables with header lines are the oldest form of internal table. n However, note that é Many statements have a different effect on internal tables with a header than they would on normal internal tables. You can then address the body separately using ">@" . ([DPSOH The CLEAR itab statement initializes only the header line, whereas in an internal with no header, it initializes the content of the entire table. You can delete the body of an internal table with a header using CLEAR itab[] or REFRESH itab. é You FDQQRW use internal tables with a header line in an object-oriented environment - that is, within classes or interfaces. © SAP AG BC401 3-32 6HOHFWLRQ2SWLRQVDQG6HOHFWLRQ7DEOHV '$7$ FDUULG7<3(VBFDUUBLG 6(/(&7237,216 6(/(&7237,216 )25 VRBFDUU)25FDUULG ( /LQNWRVHOHFWLRQVFUHHQ VRBFDUU ( 'DWDREMHFW VRBFDUU ,GHQWLFDOO\W\SHGGDWDREMHFWZLWKRXW KHDGHURUOLQNWRVHOHFWLRQVFUHHQ ¬%­'®%¯G°2±² ³%´Bµ'¶¸· ¹ºe»n­'¹6¯G° ¼e² ³6´nµ¶½· ¾ ¹¿ÁÀeÂ8à ¶ ·6Ä%Å%Å ­MÆ '$7$ VRBFDUU/,.( 5$1*(2) 5$1*(2)FDUULG Ç ­ ® Ç ÀBÂà ¶ ·%Ä6ÅÅ ­MÆ SAP AG 2002 n n Use the 6(/(&7237,21 statement to create an internal table with a header, for which the runtime system automatically creates an input dialog for value sets for a selection screen. The system automatically inserts the appropriate entries in the internal table, from the user input. For more details, refer to the keyword documentation for the 6(/(&7237,216statement. As of SAP R/3 Basis Release 4.6A onwards, you can use the 5$1*(2) addition to the 7<3(6 and '$7$ statements to define a corresponding (internal) table without a header line. © SAP AG BC401 3-33 8VLQJ,QWHUQDO7DEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV ,QWURGXFWLRQDQGDGYDQWDJHVRILQWHUQDOWDEOHV 'HILQLWLRQ 'HILQLWLRQ 2SHUDWLRQV 2SHUDWLRQV 6SHFLDOVLWXDWLRQV 6SHFLDOVLWXDWLRQV 1RWHVRQSHUIRUPDQFH 1RWHVRQSHUIRUPDQFH SAP AG 2002 © SAP AG BC401 3-34 6LQJOH5HFRUG$FFHVV&RPSOHWHO\DQG3DUWLDOO\ 4XDOLILHG.H\ 5($'7$%/(LWDE,172ZD :,7+7$%/(.(< :,7+7$%/(.(<NH\ NH\ 7DEOHNLQG 0XVWEHFRPSOHWHO\ TXDOLILHG 5($'7$%/(LWDE,172ZD :,7+.(< :,7+.(<NH\ NH\ &RPSOHWHSDUWNH\ OHIWDOLJQHGZLWKRXWJDSV %\TXDOLILHGNH\ 67$1'$5' 6257(' +$6+(' 7DEOHVFDQ %LQDU\ VHDUFK +DVK DOJRULWKP 7DEOHNLQG 67$1'$5' 7DEOHVFDQ $Q\FRPSRQHQW FRQGLWLRQ 6257(' +$6+(' %LQDU\ VHDUFK 7DEOH VFDQ 7DEOH VFDQ SAP AG 2002 n Whenever you want to read individual table lines by declaring a FRPSOHWH key, use the READ TABLE ... WITH 7$%/( KEY statement (fastest single record access by key). The runtime system supports this syntax variant especially for SORTED and HASHED tables. If the table is a STANDARD table, the runtime system performs a WDEOHVFDQ. The same applies if you have copied the values from DOO key fields of the entry to be read into the work area wa and are then use READ TABLE itab FROM wa. n The runtime system carries out the syntax variant READ TABLE ... WITH KEY (read an entry after applying DQ\ condition) using a WDEOHVFDQ The only exception to this rule applies to SORTED tables, if you fill the first Q key fields with "=" (no gaps), where Q <= number of key fields. With standard tables however, you can also sort correspondingly using SORT and then use the BINARY SEARCH addition. 6XPPDU\ n Whenever possible, use READ TABLE ... WITH 7$%/( KEY or the variant with a correspondingly-filled work area. n If you need to use READ TABLE ... WITH KEY, make your internal table a SORTED table. © SAP AG BC401 3-35 /RRS3URFHVVLQJDQG7DEOH.LQGV /223$7LWDE,172ZD ORJBH[SU :+(5(ORJBH[SU ORJBH[SU (1'/223 ORJBH[SU )LUVWQNH\ILHOGVILOOHG ZLWK ZLWKRXWJDSV 7DEOHNLQG 67$1'$5' 7DEOHVFDQ $Q\ORJLFDOH[SUHVVLRQ IRUFROXPQV 6257(' %LQDU\VHDUFKIRU VWDUWLQJSRLQW WKHQORRSRQO\ WKURXJKJURXS OHYHO +$6+(' 7DEOHVFDQ 7DEOHVFDQ SAP AG 2002 n The runtime system generally processes loops with a WHERE clause by performing a WDEOHVFDQthat is, determining whether the condition in the WHERE clause is true for each line in the table. n SORTED tables are the only exception to this rule. For these, the runtime system optimizes the runtime under the following condition: In the WHERE clause, the first Q key fields are filled with a "=" (no gaps). (Q is less than or equal to the number of all key fields). As a result, the loop is only performed on the lines that match the condition in the WHERE clause. Since the table is sorted, the first line can be specified to optimize performance at runtime (using a binary search). © SAP AG BC401 3-36 3DUWLDO6HTXHQWLDO/RRS7KURXJK6WDQGDUG7DEOHV 'HVLUHG/RRSWKURXJKGDWDUHFRUGVZKHUH&,7<)520 )5$1.)857 &$55,' $$ /+ &211,' &,7<)520 /+ 6$1)5$1&,6&2 )5$1.)857 %(5/,1 8$ 8$ )5$1.)857 1(:<25. 6257%<FLW\IURP 67$%/( &$55,' &211,' &,7<)520 /+ $VFHUWDLQVWDUWLQJSRLQW 5($'7$%/( :,7+.(<FLW\IURP )5$1.)857 75$163257,1*12),(/'6 %,1$5<6($5&+ VWDUWOLQH V\WDEL[ $VFHUWDLQHQGSRLQW 5($'7$%/(,172 :,7+.(<FLW\IURP 1(:<25. 75$163257,1*12),(/'6 %,1$5<6($5&+ HQGOLQH V\WDEL[ SAP AG 2002 /+ 8$ 8$ $$ ó %(5/,1 )5$1.)857 )5$1.)857 1(:<25. 6$1)5$1&,6&2 ,QGH[FRQWUROOHGORRS /223$7,172 )520VWDUWOLQHWRHQGOLQH (1'/223 ì n 7RUHFDS If you program a loop through a standard table to match a specific field criterion, the runtime system always executes a WDEOHVFDQ. n You can use the algorithm described here to program the runtime behavior of sorted tables: First you must sort the standard table by the desired criterion, so that you can subsequently ascertain the starting and end points in a ELQDU\VHDUFK. (The line indexes are available in the system field sy-tabix.) Finally, you can use these values to program an index-controlled loop. n Since the SORT and READ TABLE statements require additional runtime, this procedure is only useful if the loop can be repeated several times according to the field criterion. n 6XPPDU\Use SORTED tables if you want to implement partial sequential loops on internal tables (where the first Q key fields are filled with "=") or use the above algorithm. © SAP AG BC401 3-37 $FFHVV8VLQJ)LHOG6\PEROV 5($'7$%/(LWDE $66,*1,1*IV! $66,*1,1* :,7+7$%/(.(< 5($'7$%/(LWDE ,172ZD ,172 :,7+7$%/(.(< 5($'7$%/(IV!FRO $66,*1,1* $66,*1,1*IV! :,7+7$%/(.(< 5($'7$%/(ZDFRO ,172 ,172ZD :,7+7$%/(.(< ZD IV! &RS\ ZD IV! &RS\ FRO FRO FRO FRO LWDE FRO FRO FRO FRO SAP AG 2002 n Instead of READ TABLE ... INTO, you can use the READ TABLE ... ASSIGNING variant. This offers better performance at runtime for pure read accesses with a line width greater than or equal to 1000 bytes. If you then change the read line using MODIFY, READ ... ASSIGNING already improves runtime with a line width of 100 bytes. n The same applies to LOOP ... INTO in comparison with LOOP ... ASSIGNING. The LOOP ... ASSIGNING variant offers better performance at runtime for any loop of five loop passes or more. n Both field symbol variants are much faster than work area variants, in particular when you use nested internal tables. This is because, if you use work areas instead, the whole inner internal table is copied (unless you prevent this by using a TRANSPORTING addition). n Always assign a type to field symbols, if you know their static type (again, for performance reasons). n 1RWH If you use READ TABLE ... ASSIGNING the field symbol points to the originally assigned table line, even DIWHU the internal table has been sorted. n Note that when using field symbols, you cannot change key fields in SORTED or HASHED tables. Trying to do so causes a runtime error. n The following restrictions apply to LOOP ... ASSIGNING <fs>: é You cannot use the SUMstatement in control level processing. é You cannot reassign field symbols within the loop. The statements ASSIGN do TO <fs> and UNASSIGN <fs> will cause runtime errors. © SAP AG BC401 3-38 8VLQJ,QWHUQDO7DEOHV8QLW6XPPDU\ <RXDUHQRZDEOHWR l 'HILQHDQLQWHUQDOWDEOH l 3HUIRUPRSHUDWLRQVRQLQWHUQDOWDEOHV l ,GHQWLI\WDEOHNLQGVDQGXVHWKHPDSSURSULDWHO\LQ GLIIHUHQWVLWXDWLRQV SAP AG 2002 © SAP AG BC401 3-39 ([HUFLVH 8QLW 8VLQJ,QWHUQDO7DEOHV 7RSLF 6LQJOH&ROXPQ7DEOHVRIWKH7\SHVWULQJ At the conclusion of these exercises, you will be able to: • Define single-column tables of the data type VWULQJ • Split character strings with internal tables • Process internal tables in loops Now, the character string will contain PRUHWKDQRQHdata record. Extend your program in such a way that the various data records in the rows of an internal table are split. Then separate the individual data records into single components and output them as before. 3URJUDP 7HPSODWH 0RGHOVROXWLRQ =%&BB63/,7B,7$% 6$3%&B'726B63/,7B675,1* 6$3%&B7$%6B63/,7B,7$% LV\RXUWZRGLJLWJURXSQXPEHU 1-1 1-2 1-3 1-4 1-5 © SAP AG Copy your solution for the exercise in the chapter 'DWD7\SHVDQG'DWD2EMHFWVLQ 'HWDLO, =%&BB63/,7B675,1*, or the corresponding model solution 6$3%&B'726B63/,7B675,1* and give it the new name =%&BB63/,7B,7$%. Ensure that the function module %&B*(7B6(3B675,1* creates a character string consisting of 30 data records. For this you must assign a suitably typed constant (suggested name FBQXPEHU) to the parameter LPBQXPEHU. Define a single-column internal table of the type 6WDQGDUG. The column component is to have the data type VWULQJ (suggested name: LWBVHWV). Change the 63/,7 statement so that always one partial character string that contains a data record is placed into a row of its internal table. Ensure that your internal table containing the partial character strings is used for the subsequent splitting of the individual data record and output of the components in a loop. BC401 3-40 ([HUFLVH2SWLRQDO 8QLW 8VLQJ,QWHUQDO7DEOHV 7RSLF 7DEOH7\SHV At the conclusion of these exercises, you will be able to: • Select the appropriate types of internal table • Process data using internal tables Now the character string will contain GXSOLFDWH data records. Extend your program in such a way that the various data records are kept sorted in internal tables. Those data records that appear twice are to be sorted into a separate internal table. 3URJUDP 7HPSODWH 0RGHOVROXWLRQ =%&BB7$%.,1' 6$3%&B7$%6B63/,7B,7$% 6$3%&B7$%6B7$%.,1' LV\RXUWZRGLJLWJURXSQXPEHU 2-1 2-2 Copy your solution to the last exercise =%&BB63/,7B,7$% or the corresponding model solution 6$3%&B7$%6B63/,7B,7$% and give it the new name =%&BB7$%.,1'. Ensure that the function module %&B*(7B6(3B675,1* creates a character string containing duplicate data records. For this, assign the parameter LPBXQLTXH the value VSDFH. Test your program. 2-3 Define an internal table in such a way that it can contain flight data sorted by airline, flight number, and flight date (suggested name LWBIOLJKWV). Insert the separated data records (contents of the structure ZDBIOLJKW) into this internal table, instead of displaying them. (You can still use the output statement later.) Make use of the return value V\VXEUF for the ,16(57 statement to ascertain whether or not a data record appears twice. For this, you must have defined the key of your internal table accordingly. Define an additional internal table for the data records that appear twice (suggested name LWBGRXEOHV). Insert the duplicate data records into this internal table. 2-4 Display the contents of both internal tables with the flight data. © SAP AG BC401 3-41 ([HUFLVH2SWLRQDO 8QLW 8VLQJ,QWHUQDO7DEOHV 7RSLF 3URFHVVLQJ'DWD8VLQJ,QWHUQDO7DEOHV At the conclusion of these exercises, you will be able to: • Select the appropriate types of internal table • Process data using internal tables Extend your program so that it displays the flight data sorted by the flight date. The data is to be displayed in different colors, according to a key date selected by the user. If desired, the data is to be displayed using the SAP Grid Control. 3URJUDP 7HPSODWH 0RGHOVROXWLRQ =%&BB352&(66B'$7$ 6$3%&B7$%6B7$%.,1' 6$3%&B7$%6B352&(66B'$7$ LV\RXUWZRGLJLWJURXSQXPEHU 3-1 Copy your solution to the last exercise =%&BB7$%.,1' or the corresponding model solution 6$3%&B7$%6B7$%.,1' and give it the new name =%&BB352&(66B'$7$. 3-2 Define a selection screen parameter for entering the key date (suggested name SDBGDWH). Specify the default value of the key date as 30 days in the future. The user must still be able to choose the key date. Error message of the message class EF is to be displayed if the selected key date is in the past. 3-3 Make sure that the data is first displayed sorted by flight date. 3-4 © SAP AG Ensure that the individual flight dates of the internal table LWBIOLJKWV are displayed in color according to the following criteria: Use the )250$7&2/25 FROB statement and load the type group FRO. (You can reverse any color set using the )250$75(6(7 statement.) • Display flights that occurred in the past with the background color col_negative. • Display flights that occurred between today’s data and the key date with the background color col_total. BC401 3-42 • 3-5 Display flights that occurred in the past with the background color col_positive. Define a selection screen check box for displaying the data with the standard tool SAP Grid Control (suggested name SDBDOY, addition $6&+(&.%2;). Ensure that the data is only displayed in the usual ABAP list if the user does QRW check the SAP Grid Control box. Otherwise, proceed as follows: 3-5-1 Call the function module %&B$/9B/,67B287387. Terminate the program if the function module raises an exception. (In this case, there is a problem with the system configuration.) Detailed information on using the SAP Grid Control is not part of this course. For this reason, you use a function module that encapsulates all the necessary technical details, which you can treat as a “black box.” For more information on the SAP Grid Control, see: • The online documentation • The example programs under (QYLURQPHQW→([DPSOHV→&RQWURO([DPSOHV • The training course %&$%$3'LDORJ3URJUDPPLQJZLWK (QMR\6$3&RQWUROV 3-5-2 Find out about the types of the two internal tables that can/must be transferred to the function module as a parameter. Define two corresponding internal tables and an appropriate work area in your program (suggested names LWBFROBIOLJKWV, LWBFROBGRXEOHV, and ZDBFROBIOLJKW). 3-5-3 The line type of the internal table that you must/can transfer contains a column &2/25, in which you can set the color values FROBQHJDWLYH, FROBWRWDO, FROBSRVLWLYH, and FROBEDFNJURXQG for every single line. Copy the contents of the tables LWBIOLJKWV and LWBGRXEOHV to the internal tables LWBFROBIOLJKWVand LWBFROBGRXEOHV respectively. Use two loops to do this, and to fill the &2/25 column. LWBIOLJKWV: /RJLFDOFRQGLWLRQ &RORUYDOXH fldate < sy-datum col_negative fldate BETWEEN sydatum AND p_date col_total fldate > p_date col_positive Always use FROBEDFNJURXQG to display LWBGRXEOHV. © SAP AG BC401 3-43 6ROXWLRQ 8QLW 8VLQJ,QWHUQDO7DEOHV 7RSLF 6LQJOH&ROXPQ7DEOHVRIWKH7\SHVWULQJ 5(3257VDSEFBWDEVBVSOLWBLWDE TYPES: BEGIN OF st_flight_c, mandt(3) TYPE c, carrid(3) TYPE c, connid(4) TYPE n, fldate(8) TYPE n, price(20) TYPE c, currency(5) TYPE c, planetype(10) TYPE c, seatsmax(10) TYPE n, seatsocc(10) TYPE n, paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n, seatsocc_f(10) TYPE n, END OF st_flight_c, BEGIN OF st_flight, carrid(3) TYPE c, connid(4) TYPE n, fldate TYPE d, price(9) TYPE p DECIMALS 2, currency(5) TYPE c, planetype(10) TYPE c, seatsmax TYPE i, seatsocc TYPE i, END OF st_flight. &2167$176FBQXPEHU7<3(L9$/8( © SAP AG BC401 3-44 DATA: datastring TYPE string, set_string TYPE string, wa_flight_c TYPE st_flight_c, wa_flight TYPE st_flight. '$7$ LWBVHWV7<3(67$1'$5'7$%/(2)VWULQJ :,7+12181,48('()$8/7.(< ,1,7,$/6,=(FBQXPEHU START-OF-SELECTION. CALL FUNCTION ’BC401_GET_SEP_STRING’ EXPORTING LPBQXPEHU FBQXPEHU * IM_TABLE_NAME = ’SFLIGHT’ * IM_SEPARATOR = ’#’ * IM_UNIQUE = ’X’ IMPORTING ex_string = datastring EXCEPTIONS no_data = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF. SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND ’##’ IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF. 63/,7GDWDVWULQJ$7 ,1727$%/(LWBVHWV /223$7LWBVHWV,172VHWBVWULQJ © SAP AG BC401 3-45 SPLIT set_string AT ’#’ INTO wa_flight_c-mandt wa_flight_c-carrid wa_flight_c-connid wa_flight_c-fldate wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype wa_flight_c-seatsmax wa_flight_c-seatsocc wa_flight_c-paymentsum. MOVE-CORRESPONDING wa_flight_c TO wa_flight. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. (1'/223 © SAP AG BC401 3-46 6ROXWLRQ2SWLRQDO 8QLW 8VLQJ,QWHUQDO7DEOHV 7RSLF 7DEOH7\SHV 5(3257VDSEFBWDEVBWDENLQG TYPES: BEGIN OF st_flight_c, mandt(3) TYPE c, carrid(3) TYPE c, connid(4) TYPE n, fldate(8) TYPE n, price(20) TYPE c, currency(5) TYPE c, planetype(10) TYPE c, seatsmax(10) TYPE n, seatsocc(10) TYPE n, paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n, seatsocc_f(10) TYPE n, END OF st_flight_c, BEGIN OF st_flight, carrid(3) TYPE c, connid(4) TYPE n, fldate TYPE d, price(9) TYPE p DECIMALS 2, currency(5) TYPE c, planetype(10) TYPE c, seatsmax TYPE i, seatsocc TYPE i, END OF st_flight. CONSTANTS c_number TYPE i VALUE 30. © SAP AG BC401 3-47 DATA: datastring TYPE string, set_string TYPE string, wa_flight_c TYPE st_flight_c, wa_flight TYPE st_flight. DATA: it_sets TYPE STANDARD TABLE OF string WITH NON-UNIQUE DEFAULT KEY INITIAL SIZE c_number, LWBIOLJKWV7<3(6257('7$%/(2)VWBIOLJKW :,7+81,48(.(<FDUULGFRQQLGIOGDWH ,1,7,$/6,=(FBQXPEHU LWBGRXEOHV7<3(6257('7$%/(2)VWBIOLJKW :,7+12181,48(.(<FDUULGFRQQLGIOGDWH ,1,7,$/6,=(FBQXPEHU START-OF-SELECTION. CALL FUNCTION ’BC401_GET_SEP_STRING’ EXPORTING im_number = c_number * IM_TABLE_NAME = ’SFLIGHT’ * IM_SEPARATOR = ’#’ ,0B81,48( VSDFH IMPORTING ex_string = datastring EXCEPTIONS no_data = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF. © SAP AG BC401 3-48 SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND ’##’ IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF. SPLIT datastring AT ’##’ INTO TABLE it_sets. LOOP AT it_sets INTO set_string. SPLIT set_string AT ’#’ INTO wa_flight_c-mandt wa_flight_c-carrid wa_flight_c-connid wa_flight_c-fldate wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype wa_flight_c-seatsmax wa_flight_c-seatsocc wa_flight_c-paymentsum. MOVE-CORRESPONDING wa_flight_c TO wa_flight. ,16(57ZDBIOLJKW,1727$%/(LWBIOLJKWV ,)V\VXEUF! ,16(57ZDBIOLJKW,1727$%/(LWBGRXEOHV (1',) ENDLOOP. * output: ********* /223$7LWBIOLJKWV,172ZDBIOLJKW :5,7( ZDBIOLJKWFDUULG ZDBIOLJKWFRQQLG ZDBIOLJKWIOGDWH''00<<<< ZDBIOLJKWSULFH&855(1&<ZDBIOLJKWFXUUHQF\ © SAP AG BC401 3-49 ZDBIOLJKWFXUUHQF\ ZDBIOLJKWSODQHW\SH ZDBIOLJKWVHDWVPD[ ZDBIOLJKWVHDWVRFF (1'/223 6.,3 :5,7( GXSOLFDWHGDWDUHFRUGV GRE &2/25&2/B+($',1* /223$7LWBGRXEOHV,172ZDBIOLJKW :5,7( ZDBIOLJKWFDUULG ZDBIOLJKWFRQQLG ZDBIOLJKWIOGDWH''00<<<< ZDBIOLJKWSULFH&855(1&<ZDBIOLJKWFXUUHQF\ ZDBIOLJKWFXUUHQF\ ZDBIOLJKWSODQHW\SH ZDBIOLJKWVHDWVPD[ ZDBIOLJKWVHDWVRFF (1'/223 © SAP AG BC401 3-50 6ROXWLRQ2SWLRQDO 8QLW 8VLQJ,QWHUQDO7DEOHV 7RSLF 3URFHVVLQJ'DWD8VLQJ,QWHUQDO7DEOHV 5(3257VDSEFBWDEVBSURFHVVBGDWD TYPE-POOLS col. TYPES: BEGIN OF st_flight_c, mandt(3) TYPE c, carrid(3) TYPE c, connid(4) TYPE n, fldate(8) TYPE n, price(20) TYPE c, currency(5) TYPE c, planetype(10) TYPE c, seatsmax(10) TYPE n, seatsocc(10) TYPE n, paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n, seatsocc_f(10) TYPE n, END OF st_flight_c, BEGIN OF st_flight, carrid(3) TYPE c, connid(4) TYPE n, fldate TYPE d, price(9) TYPE p DECIMALS 2, currency(5) TYPE c, planetype(10) TYPE c, seatsmax TYPE i, seatsocc TYPE i, END OF st_flight. © SAP AG BC401 3-51 CONSTANTS c_number TYPE i VALUE 30. DATA: datastring TYPE string, set_string TYPE string, wa_flight_c TYPE st_flight_c, wa_flight TYPE st_flight. DATA: it_sets TYPE STANDARD TABLE OF string WITH NON-UNIQUE DEFAULT KEY INITIAL SIZE c_number, it_flights TYPE SORTED TABLE OF st_flight WITH UNIQUE KEY fldate carrid connid INITIAL SIZE c_number, it_doubles TYPE SORTED TABLE OF st_flight WITH NON-UNIQUE KEY fldate carrid connid INITIAL SIZE c_number, it_col_flights TYPE bc401_t_flights_color, it_col_doubles LIKE it_col_flights, wa_col_flight LIKE LINE OF it_col_flights. 3$5$0(7(56 SDBGDWH/,.(V\GDWXP SDBDOY$6&+(&.%2;'()$8/7 ; /2$'2)352*5$0 SDBGDWH V\GDWXP $76(/(&7,216&5((1 ,)SDBGDWHV\GDWXP 0(66$*(H EF GDWHLQWKHSDVW (1',) © SAP AG BC401 3-52 START-OF-SELECTION. CALL FUNCTION ’BC401_GET_SEP_STRING’ EXPORTING im_number = c_number * IM_TABLE_NAME = ’SFLIGHT’ * IM_SEPARATOR = ’#’ im_unique = space IMPORTING ex_string = datastring EXCEPTIONS no_data = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF. SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND ’##’ IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF. SPLIT datastring AT ’##’ INTO TABLE it_sets. LOOP AT it_sets INTO set_string. SPLIT set_string AT ’#’ INTO wa_flight_c-mandt wa_flight_c-carrid wa_flight_c-connid wa_flight_c-fldate wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype wa_flight_c-seatsmax wa_flight_c-seatsocc wa_flight_c-paymentsum. © SAP AG BC401 3-53 MOVE-CORRESPONDING wa_flight_c TO wa_flight. INSERT wa_flight INTO TABLE it_flights. IF sy-subrc <> 0. INSERT wa_flight INTO TABLE it_doubles. ENDIF. ENDLOOP. * output: ********* ,)SDBDOY ; /223$7LWBIOLJKWV,172ZDBIOLJKW 029(&255(6321',1*ZDBIOLJKW72ZDBFROBIOLJKW ,)ZDBFROBIOLJKWIOGDWHV\GDWXP ZDBFROBIOLJKWFRORU FROBQHJDWLYH (/6(,)ZDBFROBIOLJKWIOGDWHSDBGDWH ZDBFROBIOLJKWFRORU FROBWRWDO (/6( ZDBFROBIOLJKWFRORU FROBSRVLWLYH (1',) ,16(57ZDBFROBIOLJKW,1727$%/(LWBFROBIOLJKWV (1'/223 /223$7LWBGRXEOHV,172ZDBIOLJKW 029(&255(6321',1*ZDBIOLJKW72ZDBFROBIOLJKW ZDBFROBIOLJKWFRORU FROBEDFNJURXQG ,16(57ZDBFROBIOLJKW,1727$%/(LWBFROBGRXEOHV (1'/223 &$//)81&7,21 %&B$/9B/,67B287387 (;3257,1* LWBOLVW LWBFROBIOLJKWV LWBOLVW LWBFROBGRXEOHV (;&(37,216 FRQWUROBHUURU 27+(56 ,)V\VXEUF! 0(66$*(D EF (1',) © SAP AG BC401 3-54 (/6( LOOP AT it_flights INTO wa_flight. ,)ZDBIOLJKWIOGDWHV\GDWXP )250$7&2/25 FROBQHJDWLYH (/6(,)ZDBIOLJKWIOGDWHSDBGDWH )250$7&2/25 FROBWRWDO (/6( )250$7&2/25 FROBSRVLWLYH (1',) WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP. )250$75(6(7 SKIP. WRITE: / ’duplicate data records:’(dob) COLOR COL_HEADING. LOOP AT it_doubles INTO wa_flight. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP. © SAP AG BC401 3-55 &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD &RQWHQWV l 7HFKQLTXHVIRUFDOOLQJSURJUDPV l 0HPRU\PRGHO l 7HFKQLTXHVIRUSDVVLQJGDWD l 8VH SAP AG 2002 © SAP AG BC401 4-1 &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 'HVFULEHWKH6$35PHPRU\PRGHO l &DOOH[HFXWDEOHSURJUDPV l &DOOWUDQVDFWLRQV l 8VHWKHYDULRXVPHPRU\DUHDVWRSDVVGDWD SAP AG 2002 © SAP AG BC401 4-2 &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD ,QWHJUDWLRQLQ&RXUVH&RQWHQW + & " & )(,%- # & / . + & " &0 *21 #(3 " + # "& ' ! " #%$ &(' ) &* ' # 456798:<;= : 7 => :%? SAP AG 2002 © SAP AG BC401 4-3 &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD &DOOLQJSURJUDPV &DOOLQJSURJUDPV 0HPRU\PDQDJHPHQW 0HPRU\PDQDJHPHQW 3DVVLQJGDWD 3DVVLQJGDWD SAP AG 2002 © SAP AG BC401 4-4 &DOOLQJ3URJUDPV 7LPH 0DLQ PHPRU\ 0DLQ PHPRU\ 1 1 ,QVHUWSURJUDP 2 5HVWDUW (QGLQVHUW 1 1HZSURJUDP ,QVHUWLRQ 3URJUDP 3URJUDP 2 SAP AG 2002 There are two ways of starting an ABAP program from another ABAP program that is already running: • The called program is inserted, that is the current program is interrupted to run the new one. The called program is executed, and afterwards, processing returns to the program that called it. • The current program is terminated and the called program is started. Complete ABAP programs within a single user session can only run sequentially. We refer to this technique as VHTXHQWLDOFDOOLQJ. If you want to run functions in parallel, you must use function modules. For further information about this technique, refer to the course %& &RPPXQLFDWLRQ,QWHUIDFHVLQ$%$3 or the documentation for the &$//)81&7,2167$57,1*1(:7$6. statement. © SAP AG BC401 4-5 &DOOLQJDQ([HFXWDEOH3URJUDP 3URJUDP 68%0,7SURJBQDPHB 3URJUDP 5HVWDUW ,QVHUWLRQ 68%0,7SURJBQDPHB $1'5(7851 ,QVHUWLRQ 68%0,7SURJBQDPHB 9,$6(/(&7,216&5((1 $1'5(7851 SURJBQDPHB 352*5$0 SURJBQDPHB 352*5$0 /LVW ) /LVW ) 6HOHFWLRQ6FUHHQ SURJBQDPHB /LVWH 352*5$0 ) ) SAP AG 2002 To start an executable program, use the 68%0,7 statement. If you use the 9,$6(/(&7,216&5((1 addition, the system displays the standard selection screen of the program (if one has been defined). If you use the $1'5(7851 addition, the system resumes processing with the first statement after the 68%0,7 statement once the called program has finished. For further information, refer to the documentation for the 68%0,7 statement. © SAP AG BC401 4-6 &DOOLQJD7UDQVDFWLRQ 3URJUDP 3URJUDP7UDQVDFWLRQ 5HVWDUW 6FUHHQ /($9(7275$16$&7,21 ’T_CODE’ >$1'6.,3),5676&5((1@ 6FUHHQ ) ,QVHUWLRQ &$//75$16$&7,21 ’T_CODE’ >$1'6.,3),5676&5((1@ 6FUHHQ 6FUHHQ ) TCODE 6$30WBQDPH /($9(352*5$0 6$30WBQDPH /($9(352*5$0 SAP AG 2002 With the /($9(7275$16$&7,21 T_CODE statement you terminate the current program and start the transaction with transaction code 7B&2'( The statement is the equivalent to entering Q<T_CODE> in the command field. &$//75$16$&7,21 ’T_CODE’ allows you to insert ABAP programs that have a transaction code. To terminate an ABAP program, use the /($9(352*5$0 statement. If the statement is used in a program that you called using &$//75$16$&7,21 ’T_CODE’ or 68%0,7prog_name $1'5(7851, the system resumes processing at the next statement after the call in the calling program. Otherwise, the user returns to the application menu from which he or she started the program. If you use the$1'6.,3),5676&5((1 addition, the system does QRW display the VFUHHQFRQWHQWV of the first screen. However, it does process the flow logic. If the transaction T_CODE you called with &$//75$16$&7,21 uses update techniques, you can use the 83'$7( addition to specify the update technique (asynchronous (default), synchronous, or local) that the program should use. For further information, refer to course %& 3URJUDPPLQJ'DWDEDVH8SGDWHV and the online documentation. © SAP AG BC401 4-7 &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD &DOOLQJSURJUDPV &DOOLQJSURJUDPV 0HPRU\PDQDJHPHQW 0HPRU\PDQDJHPHQW 3DVVLQJGDWD 3DVVLQJGDWD SAP AG 2002 © SAP AG BC401 4-8 /RJLFDO0HPRU\0RGHO 8VHUWHUPLQDOVHVVLRQ ([WHUQDOVHVVLRQ ZLQGRZ ([WHUQDOVHVVLRQ ZLQGRZ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP $%$3PHPRU\ $%$3PHPRU\ ,QWHUQDOVHVVLRQ ,QWHUQDOVHVVLRQ 3URJUDP 6$3PHPRU\ SAP AG 2002 The way in which the main memory is organized from the program’s point of view can be represented in the above logical model. There is a distinction between internal and external sessions: • Generally, an H[WHUQDOVHVVLRQ is connected to an R/3 window. You can create a new session by choosing 6\VWHP→1HZ6HVVLRQ or by entering R<T_CODE> in the command field. You can have up to six external sessions open simultaneously in one terminal session. • External sessions are subdivided into LQWHUQDOVHVVLRQV (placed on a VWDFN). Each program that you run occupies its own internal session. Each external session can contain up to nine internal sessions. Data for a program is RQO\YLVLEOHZLWKLQan internal session. The visibility of the data is generally restricted to the relevant program. The following slides illustrate how the stack inside an external session changes with various program calls. © SAP AG BC401 4-9 ,QVHUWLQJD3URJUDP External session (window) 1 External session (window) 2 ABAP memory 1 ABAP memory 2 User terminal session ,QWHUQDOVHVVLRQ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP SAP memory SAP AG 2002 © SAP AG BC401 4-10 ,QVHUWLQJD3URJUDP User terminal session ,QVHUWLRQ External session (window) 1 External session (window) 2 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP ABAP memory 2 ABAP memory 1 ,QWHUQDOVHVVLRQ ,QWHUQDOVHVVLRQ 3URJUDP SAP memory SAP AG 2002 When you insert a program, the system creates a new internal session, which in turn creates a new program context. The new session is placed on the stack The program context of the calling program also remains intact. © SAP AG BC401 4-11 7HUPLQDWLQJWKH,QVHUWHG3URJUDP External session (window) 1 External session (window) 2 ABAP memory 1 ABAP memory 2 User terminal session ,QWHUQDOVHVVLRQ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP SAP memory SAP AG 2002 When the called (inserted) program finishes, its internal session (the top one in the stack) is deleted. Processing is resumed in the next-highest internal session in the stack. © SAP AG BC401 4-12 5HVWDUWLQJDQ([HFXWDEOH3URJUDP User terminal session External session (window) 1 External session (window) 2 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP ABAP memory 2 ABAP memory 1 ,QWHUQDOVHVVLRQ ,QWHUQDOVHVVLRQ 3URJUDP SAP memory SAP AG 2002 When you end a program and start a new one, there is a distinction between calling an executable program and calling a transaction, with regard to memory areas. © SAP AG BC401 4-13 5HVWDUWLQJDQ([HFXWDEOH3URJUDP User terminal session 5HVWDUW External session (window) 1 External session (window) 2 3URJUDPP 3URJUDPP ,QWHUQDOVHVVLRQ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP ABAP memory 2 ABAP memory 1 ,QWHUQDOVHVVLRQ ,QWHUQDOVHVVLRQ 3URJUDP SAP memory SAP AG 2002 If you call an executable program using its program name (terminating the calling program), the system deletes the internal session of the program that you are terminating (the top one from the stack). The system creates a new internal session, which in turn creates the program context of the called program. The new session is placed on the stack Existing program contexts remain intact. The topmost internal session on the stack is replaced. © SAP AG BC401 4-14 5HVWDUWLQJD7UDQVDFWLRQ User terminal session ([WHUQDOVHVVLRQ ZLQGRZ External session (window) 2 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP ABAP memory 2 $%$3PHPRU\ ,QWHUQDOVHVVLRQ ,QWHUQDOVHVVLRQ 3URJUDP SAP memory SAP AG 2002 © SAP AG BC401 4-15 5HVWDUWLQJD7UDQVDFWLRQ User terminal session 5HVWDUW FRPSOHWH LQLWLDOL]DWLRQ External session (window) 2 ABAP memory 2 $%$3PHPRU\ ([WHUQDOVHVVLRQ ZLQGRZ ,QWHUQHU0RGXV 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP SAP memory SAP AG 2002 If you start a program using its WUDQVDFWLRQFRGH(that is, if one was defined), DOOof the internal sessions on the stack are deleted. The system creates a new internal session, which in turn creates the program context of the called program. After the call, the ABAP memory is LQLWLDOL]HG. © SAP AG BC401 4-16 &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD &DOOLQJSURJUDPV &DOOLQJSURJUDPV 0HPRU\PDQDJHPHQW 0HPRU\PDQDJHPHQW 3DVVLQJGDWD 3DVVLQJGDWD SAP AG 2002 © SAP AG BC401 4-17 2YHUYLHZ3DVVLQJ'DWD%HWZHHQ3URJUDPV 6$3PHPRU\ 6(7*(7SDUDPHWHUV 3 $%$3PHPRU\ 2 3URJUDP$ ,QWHUIDFH 1 3URJUDP% 4 DB 5 SAP AG 2002 There are various ways of passing data to programs running in separate internal sessions: You can use: The interface of the called program (usually a standard selection screen) ó ABAP memory ì SAP memory ö Database tables ú Local files on your presentation server The following slides deal with the first three of these methods. For further information regarding the passing of data using database tables or the VKDUHGEXIIHU, refer to the documentation for the (;3257 and ,03257 statements. For further information on transferring data between an ABAP program and a presentation server, refer to the documentation for the function modules *8,B83/2$' and *8,B'2:1/2$'. © SAP AG BC401 4-18 3DVVLQJ'DWD8VLQJWKH3URJUDP,QWHUIDFH 6WDQGDUGVHOHFWLRQVFUHHQ 3URJUDP% Data 3URJUDP$ SAP AG 2002 When you call ABAP programs that have a standard selection screen, you can pass data for the input fields in the call. There are two ways to do this: • By specifying a variant for the selection screen when you call the program • By specifying values for the input fields when you call the program © SAP AG BC401 4-19 3UHDVVLJQLQJ9DOXHVIRU,QSXW)LHOGV 3DWWHUQIRU68%0,7 VWDWHPHQWLQVHUWVWKH DSSURSULDWHIUDPHIRUWKH SURJUDPFDOOLQWRWKH VRXUFHFRGH @BADCE<F GIHJDGKGLEF(A M2M2M M2M2M M2M2M NO P Q R(S TUO O Q R V WYX/Z[\^] '$7$VHW7<3(_/,.(5$1*(2)W\SH_GDWDREMHFW` 68%0,7SURJBQDPH$1'5(7851>9,$6(/(&7,216&5((1@ :,7+SDUDPHWHU(4_1(_YDO :,7+VHOBRSW(4_1(_YDO6,*1 , _ ( ` :,7+VHOBRSW%(7:((1YDO$1'YDO6,*1 , _ ( ` :,7+VHOBRSW127%(7:((1YDO$1'YDO6,*1 , _ ( ` :,7+VHOBRSW,1VHW SAP AG 2002 The :,7+ addition to the 68%0,7 statement allows you to preassign values for parameters and selection options on a standard selection screen of the called executable program. The abbreviations "(4, 1(, ...; ,, (" have the same meanings as with selection options. If you want to pass several selections for a selection option, you can use the 5$1*( statement instead of individual :,7+additions. The RANGES statement creates a selection table, which you can fill as though it were a selection option. You then pass the whole table to the executable program. If you want to display the standard selection screen when you call the program, use the 9,$ 6(/(&7,216&5((1 addition. When you use the 68%0,7 statement, use the Pattern function in the ABAP Editor to insert an appropriate statement pattern for the program you want to call. It automatically supplies the names of the parameters and selection options that are available on the standard selection screen. For further information about working with variants and about other syntax variants of the :,7+ addition, refer to the documentation for the 68%0,7 statement. © SAP AG BC401 4-20 $%$30HPRU\DQG6$30HPRU\ 8VHUWHUPLQDOVHVVLRQ ,QWHUQDOVHVVLRQ ,QWHUQDOVHVVLRQ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP $%$3PHPRU\ ([WHUQDOVHVVLRQ ZLQGRZ $%$3PHPRU\ ([WHUQDOVHVVLRQ ZLQGRZ 3URJUDP ,QWHUQDOVHVVLRQ 3URJUDP 6$3PHPRU\ 6(7*(7SDUDPHWHUV SAP AG 2002 You can use SAP memory and ABAP memory to pass data between programs. n 6$3PHPRU\ is a user-specific memory area for storing ILHOGYDOXHV. It is only of limited value for passing data between internal sessions. Values in SAP memory are retained for the duration of the user’s terminal session. The memory can be used between sessions in the same terminal session. You can use the contents of SAP memory as default values for screen fields. All H[WHUQDOVHVVLRQV can use the SAP memory. n $%$3PHPRU\ is also user-specific. There is a local ABAP memory for each external session. You can use it to exchange DQ\$%$3YDULDEOHV (fields, structures, internal tables, complex objects) between the LQWHUQDOsessions in any one external session. When the user exits an external session (L in the command field), the corresponding ABAP memory is automatically initialized or released. © SAP AG BC401 4-21 3DVVLQJ'DWD8VLQJWKH$%$30HPRU\ ,QWHUQDOVHVVLRQ $%$3PHPRU\ 0<B,' 352*5$0S '$7$SBVSIOL7<3(VSIOL LWBVSIOL7<3(67$1'$5'7$%/( 2)VSIOL (;3257 ZDB ZDBIOL)520SBVSIOL LWBVSIOL 720(025<,' 0<B,' ZDBIOL LWBVSIOL ,QWHUQDOVHVVLRQ 0<B,' 352*5$0S '$7$SBVSIOL7<3(VSIOL LWBVSIOL7<3(67$1'$5'7$%/( 2)VSIOL ,03257 ,03257 ZDB ZDBIOL72SBVSIOL LWBVSIOL )5200(025<,' 0<B,' SAP AG 2002 The (;3257720(025< statement allows you to copy any number of ABAP data objects with their current values to the ABAP memory (data cluster). The,' addition enables you to identify different clusters (maximum of 60 characters). If you use a new (;3257720(025< statement for an existing data cluster, the new one will overwrite the old. The ,03257)5200(025<,' statement allows you to copy the data from the ABAP memory into corresponding data objects of your ABAP program. It is also possible to only import parts of data clusters using ,03257. The data objects that are to receive the data from the ABAP memory cluster must have the same types in both the calling and the called programs. To release a data cluster, use the )5((0(025<,' statement. Bear in mind that when you call programs using transaction codes, you can RQO\ use the ABAP memory to pass data ZKHQLQVHUWLQJ(&$//75$16$&7,21). © SAP AG BC401 4-22 3DVVLQJ3DUDPHWHUV8VLQJWKH6$30HPRU\ Program A $LUOLQH RU /+ &RQQHFWLRQ _ 6(7 6(73$5$0(7(5,' &21 ),(/'VG\QBFRQQFRQQLG &$//75$16$&7,21 6$3PHPRU\ &$5 &21 /+ Program B $LUOLQH /+ &RQQHFWLRQ _ *(7 RU *(73$5$0(7(5,' &21 ),(/'VG\QBFRQQFRQQLG SAP AG 2002 You can define memory areas (parameters) in the SAP memory in various ways: • By creating input/output fields with reference to the ABAP Dictionary. These take the parameter name of the data element to which they refer. Alternatively, you can enter a name in the attributes of the input/output fields. Here, you can also choose whether the entries from the field should be transferred to the parameter (SET), or whether the input field should be filled with the value from the parameter (GET). To find out about the names of the parameters assigned to input fields, display the field help for the field (F1), then choose 7HFKQLFDOLQIR. • You can also fill the memory areas directly using the 6(73$5$0(7(5,'’PAR_ID’ ),(/'varstatement and read them using *(73$5$0(7(5,' PAR_ID ),(/' var • Finally, you can define parameters in the 2EMHFW1DYLJDWRU and let the user fill them with values. © SAP AG BC401 4-23 3UHYLHZ3DVVLQJ'DWD8VLQJDQ,QWHUQDO7DEOH 3URJUDP 3URJUDP7UDQVDFWLRQ '$7$ ELBLWDE7<3(7$%/(2)EGFGDWD ELBZD7<3(EGFGDWD T_CODE ELBLWDE ILOOELBLWDE FDOORWKHUSURJUDP &$//75$16$&7,21 7B&2'( 86,1*ELBLWDE ,)V\VXEUF (/6( VWVFUHHQ QGVFUHHQ ) 6$30WBQDPH /($9(352*5$0 SAP AG 2002 The &$//75$16$&7,21 T_CODE 86,1*bi_itab statement allows you to insert the transaction T_CODE, and the screens are processed according to the internal table bi_itab. 7KLVLQWHUQDOWDEOHPXVWEHW\SHGDFFRUGLQJWRWKHVWUXFWXUHEGFGDWDDQGILOOHG DSSURSULDWHO\ The 02'( addition allows you to specify whether the screen contents should all be displayed (’A’ - the default setting), only when an error occurs (’E’), or not at all (’N’). The 0(66$*(6,172mess_itab addition is used to specify where the system messages sent during the execution of the called transaction are written. 7KHLQWHUQDOWDEOHPXVWEHW\SHGDFFRUGLQJWRWKHVWUXFWXUHEGFPVJFROO You can find out if the transaction was executed successfully from the system field V\VXEUF. This technique is useful if, for example: • You are processing in the foreground, but the input fields have not been filled using GET parameters • You want to process the transaction in the background. In this case, you normally have to pass function codes as well. This technique is also RQH of the possible ways of transferring data from non-SAP systems. To do so the internal table in the EGFGDWD format must be filled completely. © SAP AG BC401 4-24 )LHOGVRIWKH*OREDO7\SHEGFGDWD SURJUDP G\QSUR G\QEHJLQ IQDP IYDO 'HVFULSWLRQ `IF^abcFLJedfA J<dgE t o<F E EAuAvedxw EF y<kBF CGIF Eo acFnp y<k E<i pxAeJdgE y<k E<i pgzJi9v E 1RWHZKHQ ILOOLQJ h A i jlk AlmC G FnEoDacF^pqarAsCo<FnEDE<A h Ai jxk AxmC G FnE oDacF^pqaIAsCoeFnEDE<A { |}{~^acFmCG FnE oDarFnpqarA CoeFnE E<Ae aeG% EF2k CE{{ )LHOGQDPH /HQJWK J CE C EADCk Gk zeE SAP AG 2002 Filling the internal table in batch input format: • Each screen that is to be processed and filled automatically in the transaction must be identified by a line, in which only the fields SURJUDP, G\QSUR and G\QEHJLQ are filled. • After the record that identifies the screen, use a separate EGFGDWD record for each field you want to fill. These records use the table fields IQDP and IYDO. The following fields can be filled: - - Input/output fields, with data The command field (EGFBRNFRGH), with function codes The cursor position field (EGFBFXUVRU), with field names. You also use the &$//75$16$&7,21 technique to transfer GDWDIURPH[WHUQDOV\VWHPV. Further information on this topic is available in the course %& 'DWD7UDQVIHU and in the online documentation. © SAP AG BC401 4-25 ([DPSOH3DVVLQJ'DWD8VLQJDQ,QWHUQDO7DEOH SURJUDP G\QSUR Dr<D e<Ie D< I< G\QEHJLQ e IQDP IYDO <<r¢¡£ ¤r¥<¥e¦<§r¨§<©Dªc¦!« <D < ¬ r­D®¯¡£ ¤c¥<¥e¦e§¨£°¨±c« <!r<² ! '$7$ EGFGDWD ZDBEGFGDWD7<3(EGFGDWD LWBEGFGDWD/,.(7$%/(2)ZDBEGFGDWD ILOOWKHEGFGDWDWDEOH &$//75$16$&7,21 %&B&$/'B&5(B&867 86,1*LWBEGFGDWD 86,1* 02'( 1 02'( ,)V\VXEUF! 0(66$*(:,7+V\VXEUF (1',) <³r 6DYH ,'IRUFRPPDQG ILHOG SAP AG 2002 This example refers to the transaction %&B&$/'B&7$B8. If you request the creation of a new customer entry here, the transaction %&B&$/'B&5(B&867 is inserted. This transaction has not implemented an import from the ABAP memory, and its input fields are not set as *(7 parameters. The customer data is therefore passed using an internal table and the transaction processed in the background. If the operation is successful, the new customer data record can be entered in the waiting list. The relevant internal table in EGFGDWD format is shown above. current_name is the customer name adopted from the input field at runtime, current_city is the city. You address the command field using %'&B2.&2'(. Here you enter the function code that is triggered by the user choosing a function key, pushbutton, or menu entry during the dialog flow (or by entering a code directly in the command field). © SAP AG BC401 4-26 &DOOLQJ3URJUDPVDQG3DVVLQJ'DWD8QLW6XPPDU\ <RXDUHQRZDEOHWR l 'HVFULEHWKH6$35PHPRU\PRGHO l &DOOH[HFXWDEOHSURJUDPV l &DOOWUDQVDFWLRQV l 8VHWKHYDULRXVPHPRU\DUHDVWRSDVVGDWD SAP AG 2002 © SAP AG BC401 4-27 ,QWURGXFWLRQWR2EMHFW2ULHQWHG3URJUDPPLQJ &RQWHQWV l 3URFHGXUDOSURJUDPPLQJ l 2EMHFWRULHQWHGSURJUDPPLQJ l $LPVRIWKH$%$32EMHFWVSURJUDPPLQJODQJXDJH SAP AG 2002 © SAP AG BC401 5-1 ,QWURGXFWLRQWR2EMHFW2ULHQWHG3URJUDPPLQJ8QLW 2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 1DPHWKHPRVWVLJQLILFDQWGLIIHUHQFHVEHWZHHQ SURFHGXUDODQGREMHFWRULHQWHGSURJUDPPLQJ l 6WDWHWKHDLPVEHKLQGGHYHORSLQJWKH$%$3 2EMHFWVSURJUDPPLQJODQJXDJH SAP AG 2002 © SAP AG BC401 5-2 ,QWURGXFWLRQWR2EMHFW2ULHQWHG3URJUDPPLQJ ,QWHJUDWLRQLQ&RXUVH&RQWHQW 8 F 5 ? G C ? < ? A$DE = 5 78 C ? < ?H BJI =$K < C = <? 7@ 4657 8(9;: 8(< => 8?$@ A ?B @ = 5 ! "$.0/ "$# # % &('*)+-, ' + "$3 " " &1 ) " / / % & '*2 LNMPOGQ R$STVU S Q U$W SX SAP AG 2002 © SAP AG BC401 5-3 +LVWRU\RI3URJUDPPLQJ/DQJXDJHV Machine language Assembler _ `[` acb*acd Y[Z]\^Z $%$32EMHFWV SAP AG 2002 n Before ABAP, SAP used a macro assembler. n $%$3 was created with the intention of improving reporting. ABAP developed almost independently as an in-house programming language, although it was influenced by other programming languages, for example, COBOL and PASCAL. n $%$32EMHFWV is a true extension of ABAP. ABAP Objects unites the most promising aspects of other object-oriented programming languages, such as Java, C++, and Smalltalk. © SAP AG BC401 5-4 ,QWURGXFWLRQ3URJUDPPLQJ0RGHOV 3URFHGXUDOSURJUDPPLQJ 3URFHGXUDOSURJUDPPLQJ 2EMHFWRULHQWHGSURJUDPPLQJ 2EMHFWRULHQWHGSURJUDPPLQJ SAP AG 2002 © SAP AG BC401 5-5 &KDUDFWHULVWLFVRI3URFHGXUDO3URJUDPPLQJ e0 ^fgihf e0 [f Pgihf &KDUDFWHULVWLFV e^ 0fgihf l l e^ [f Pghf e^ 0fP ghif l 6HSDUDWLRQRIIXQFWLRQVDQGGDWD 3RVVLELOLW\RIHQFDSVXODWLQJ IXQFWLRQVXVLQJPRGXODUL]DWLRQ 'LUHFWDFFHVVWRGDWDSRVVLEOH YLVLELOLW\" j jkG kGlG lGmqmnrn o o p p6l l j jkG kGlG l(mmn n o o p6 p6l l jP jkG kGlG lGmmn-n o o p6 p6l l jP jkG kGlG lGmqmqn-nro o pP pl l jP jkG kGlG lGmmn n-o o p6 pl l jP jkG kGlG lGmqmnrn o o pP p6l l j( jPk( kGl( lGmqmqn-nro o pP pPl l j jPkG kGlG lGmmn n o o p6 p6l l SAP AG 2002 n Information systems were previously defined primarily by their functions: Data and functions were stored separately and linked using input-output relationships. © SAP AG BC401 5-6 7\SLFDO$%$33URJUDP 5(3257=$%$3B'(02 5(3257=$%$3B'(02 7<3(6 7<3(6 l 7\SHGHILQLWLRQV '$7$ '$7$ l 'DWDGHFODUDWLRQV l 0DLQSURJUDP 3(5)250IRUP 3(5)250IRUP &$//)81&7,21 &$//)81&7,21 )% )% &$//)81&7,21 &$//)81&7,21 )% )% )250I )250I (1')250 (1')250 &DOOLQJVXEURXWLQHV &DOOLQJIXQFWLRQPRGXOHV l 'HILQLWLRQRIVXEURXWLQHV SAP AG 2002 n A typical ABAP program consists of type definitions and data declarations, which describe the blueprint of the data the program uses when it is executed. n To make your program more readable and for better program structure, it is recommended that you work with modularization units (encapsulated units with functions), such as form routines or function modules. These components can be reused in many different programs. © SAP AG BC401 5-7 $%$30DLQ0HPRU\DQG)XQFWLRQ*URXSV ,QWHUQDOVHVVLRQ sutJv wyx*t{z x{J x Pv |ix}v w~N{|iJ y |-Jvy y(x v )XQFWLRQJURXS ¥¦ §¨©¦NªN©«-© g ][N ¢¡ g ][N 6Pg VVV ¤ ¤ ¤ £ )XQFWLRQJURXS ¥;¦ §¨©¦Nª©« © ;VNJV g Interface g ][N ¢¡ g ][N £ Interface SAP AG 2002 n This slide provides an overview of the main program components during program execution in an internal session (main memory area on application server). n The loaded main program and the two function groups with their encapsulated modules (the function modules) are both in separate memory areas. n From the main program, you can use function modules to access function group components, for example their global data. Therefore, a function group is a unit consisting of data and functions that manage this data. n A user "client" (here, the main program) can only access the function groups and their services using the interface, that is the function modules. The function group acts as a "server", because it provides services. © SAP AG BC401 5-8 )XQFWLRQ*URXS([DPSOH )81&7,21322/VBYHKLFOH )81&7,21322/VBYHKLFOH VSHHGLVDJOREDOYDULDEOH VSHHGLVDJOREDOYDULDEOH XVHGLQWKHIXQWLRQSRRO XVHGLQWKHIXQWLRQSRRO '$7$VSHHG7<3(, '$7$VSHHG7<3(, )81&7,21,1&B63((' )81&7,21,1&B63((' $''LPSBVSHHG72VSHHG $''LPSBVSHHG72VSHHG (1')81&7,21 (1')81&7,21 ¬®­y¯±° ²³´ ½ ­y¯®°²³´ ¯u¾ ²¼®Á¾ ¯¶µu·0´¸­y¹»º³(²¼ ½ ´y·°´ ¹±ÁÁ ö´ ¯®²·´ ½yÄ ° ¿À¿³q¯ Ä µ · 6B9(+,&/( VSHHG )81&7,21'(&B63((' )81&7,21'(&B63((' 68%75$&7,03B63(('IURPVSHHG 68%75$&7,03B63(('IURPVSHHG (1')81&7,21 (1')81&7,21 GÅVÆ P(ÅNVÆP Ç Pg Å]ÆP g Æ )81&7,21*(7B63((' )81&7,21*(7B63((' H[SBVSHHG H[SBVSHHG VSHHG VSHHG (1')81&7,21 (1')81&7,21 SAP AG 2002 n The function group s_vehicle provides a user or client with the services inc_speed, dec_speed, and get_speed. n These services make up the function group interface and access the internally encapsulated component speed. © SAP AG BC401 5-9 8VHRI)XQFWLRQ*URXS 5(3257]YHKLFOHGHPR 5(3257]YHKLFOHGHPR 7<3(6 7<3(6 È Ä ½ ­ ¯°y²³´ ³À¯¶¹ µu· ÄÉ ·0´ É ¯ ½ ­y¯±° ´ à ²¼ Ä ² ­y¿(Á;¾Ë´ ­ ¾ÊÁ*¾ ½ ²¼u³À¾ ²³(´y¯¶µ¸·´¸­y¹ '$7$ZDBFDU7<3( '$7$ZDBFDU7<3( QRGLUHFWDFFHVVWRVSHHG QRGLUHFWDFFHVVWRVSHHG 6B9(+,&/( XVHIXQFWLRQVRISRRO XVHIXQFWLRQVRISRRO VSHHG &$//)81&7,21 &$//)81&7,21 ,1&B63((' ,1&B63((' GÅVÆ &$//)81&7,21 &$//)81&7,21 *(7B63((' *(7B63((' P(ÅNVÆP Ç Pg Å]ÆP g Æ &$//)81&7,21 &$//)81&7,21 6723 6723 SAP AG 2002 n The main program cannot access speed directly. © SAP AG BC401 5-10 6HYHUDO,QVWDQFHVRI2QH)XQFWLRQ*URXS Ì ³À¾¹ ¿ ÄÍ ´y¯ Ä 6B9(+,&/( Ä Á;¼u³(°*¿(Á*¾ Ï Ã Ãy³²³´ Ä ³À¯uµ ¯±­ Á;·}´ ½ ¯®Ã¶²¼Á;³À·±¾y¹ÁÁyÃгq¾ ¿ Í ¹®´y¾y¾³ Î ¯ É¶Î Ä ¿ Ä Ã É ¿(ÁѺ³(²¼ ³À¯ ³À¾Ê²· Ä ²³´y¯ VSHHG GÅVÆ GÅNVÆ6 Ç Pg ÅÆ6 g Æ SAP AG 2002 n If the main program is to work with several vehicles, this is not possible without extra programming and administration effort. © SAP AG BC401 5-11 ,QVWDQWLDWLRQDQG2EMHFW2ULHQWHG/DQJXDJHV È ²¼Á¾ °;¿ Ä VSHHG ¾c² Ä ­y¿(²³q¹u¿(Á³À¯ ½ ´ Ä ²(²·³ Î ÄÉ ¾y¾;Ô Î Á Ä Á;¾ËÒG´ Ä˽ ­y¯±Ã ·0Á ½ ­¸²(ÁÑ´ ¿ Ä ¯±° ¯ ÎÓ Á°²¾;Ô ¿(­uÁ¹u·³q¯±²uÒ(² Í ´ µ­ ÄÉ ¹®ÁÑ´ Á*¯±² Ä · ¿ ÎÓ Á°²Õ´y·³PÁ¯²GÁÃ Ä µ®Á*¾ VSHHG VSHHG VSHHG SAP AG 2002 n The ability to create multiple instances of a "class", such as a vehicle, is one of the central attributes of object-oriented languages. © SAP AG BC401 5-12 ,QWURGXFWLRQ3URJUDPPLQJ0RGHOV 3URFHGXUDOSURJUDPPLQJ 3URFHGXUDOSURJUDPPLQJ 2EMHFWRULHQWHGSURJUDPPLQJ 2EMHFWRULHQWHGSURJUDPPLQJ SAP AG 2002 © SAP AG BC401 5-13 3URJUDPPLQJ0RGHOV 2EMHFWPRGHODV DEVWUDFWLRQRIUHDO ZRUOG 'DWDDQGIXQFWLRQV Ö ØNÙn Ù ØNÙqn Ù {xt ×cv tJz ØÙqn-Ù jPkGlGmn o p6lÚ ØNÙn-Ù ØNÙn-Ù jkGlGmn o p6lÚ ØÙn-Ù jkGlGmn o p6lÚ j(k(lGmn-o pPl$Ú ØÙn-Ù j( jk( kGl( lGmqmqn-nro o pP pl l j( j(k( k(l lmmnrn-o o p6 pPl l j( j(k( k(l lGmmn-n-o o pP pPl l j jkG kGl( lGmmn n-o o p6 pl l j jkG kGlG l(mmn n o o p6 p6l l j(k(lmn-o pl$Ú jkGlGmn o p6lÚ j( jk( k(lG lmmn-nro o pP pPl l j jkG kGlG l(mqmnrn o o p p6l l j jPkG k(lG lmmn n o o p6 p6l l jPkGlGmn o p6lÚ ØNÙn-Ù jkGlGmqnro plÚ j(k(lmnro p6l$Ú SAP AG 2002 n The left part of the slide shows that, with procedural software systems, data and functions are often: é Created separately é Stored separately é Linked with input-output relations n Objects form capsules containing the data itself and the behavior of that data. Objects enable you to draft a software solution that is a one-to-one reflection of the real-life problem area. © SAP AG BC401 5-14 &KDUDFWHULVWLFVRIWKH2EMHFW2ULHQWHG$SSURDFK l Ö {x;t×uvy(tJz l l l l l 2EMHFWVDUHDQDEVWUDFWLRQRIWKHUHDO ZRUOG 3URFHVVHVFDQEHLPSOHPHQWHG UHDOLVWLFDOO\ 2EMHFWVDUHXQLWVPDGHXSRIGDWDDQGWKH IXQFWLRQVEHORQJLQJWRWKDWGDWD ,PSURYHVVRIWZDUHVWUXFWXUHDQG FRQVLVWHQF\LQWKHGHYHORSPHQWSURFHVV 0DLQWHQDQFHUHTXLUHPHQWVDUHUHGXFHG 0RGHOHUHQGXVHUDQGGHYHORSHUDUHDOO LQFOXGHGLQDQDO\VLVDQGGHVLJQSURFHVV SAP AG 2002 n In object-oriented programming, data and functions are developed together. Object orientation focuses on objects that represent either abstract or concrete things in the real world. They are first viewed in terms of their characteristics, which are displayed using the object’s internal structure and attributes (data). n The EHKDYLRURIREMHFWV is described through methods (functions) and events. n Consistency throughout the software development process: The "language" used in the various phases of software development (analysis, specification, design, and implementation) is uniform. Ideally, changes made to the design during the implementation phase will flow back into the design automatically. n The aim is to use this concept to: é Implement processes realistically and, at the same time, better involve the modeler and developer in the software design é Achieve optimized structuring and maintenance of the software and hence reduce the work required © SAP AG BC401 5-15 7HFKQLFDO,PSOHPHQWDWLRQRIWKH2EMHFW2ULHQWHG $SSURDFK l (QFDSVXODWLRQRIGDWDDQGIXQFWLRQV l 3RO\PRUSKLVPIRUVXSSRUWRIJHQHULF SURJUDPPLQJ Û pÜGÝß l ,QKHULWDQFH V Æ f6P ¡ j( k( Gl Gm nro p6l$ Ú j( k( Gl( Gmq n-o pP l$ Ú Û pÜGÝ0à ÜPo ÚGâGã ÙäÀå(ÜPÙqn Ù Û pÜGÝ0á Û pPÜ(Ý[Þ f66 V Ø NÙ n Ù f6 £ l ,PSURYHGVWUXFWXULQJDQGFRQVLVWHQF\LQWKHVRIWZDUH GHYHORSPHQWSURFHVV SAP AG 2002 n (QFDSVXODWLRQ Encapsulation means that the implementation of an object is hidden from other components in the system, so that they cannot make assumptions about the internal status of the object and therefore dependencies on specific implementations do not arise. n 3RO\PRUSKLVP Polymorphism (ability to have multiple forms) in the context of object technology signifies that objects in different classes react differently to the same messages. n ,QKHULWDQFH Inheritance defines the implementation relationship between classes, in which one class (the subclass) shares the structure and the behavior defined in one or more other classes (superclasses). Note: ABAP Objects only allows single inheritance. © SAP AG BC401 5-16 &OLHQW6HUYHU%HKDYLRU l l l 2EMHFWVEHKDYHWRZDUGVHDFKRWKHUMXVWOLNH FOLHQWVHUYHUV\VWHPV 2EMHFWVQRUPDOO\DGRSWERWKUROHV 5HVSRQVLELOLWLHVPXVWEHVSHFLILHGEHWZHHQWKHREMHFWV 0HWKRGV &$//0(7+2'VHUYHU!GRBLW FDOOBLW 'DWD 0HWKRGV GRBLW 'DWD æçuèêéÊçuè ëíìîçÊïð SAP AG 2002 n Objects behave like client/server systems: When an object calls a method of another object, it automatically becomes the client of the other (server) object. This gives rise to two conditions: • The client object must adhere to the SURWRFRO of the server object • The protocol must be clearly described so that a potential client can follow it without problem n Objects normally adopt both roles Every object is a potential server object, and when it is called by a method of another object, it becomes a client object too. n Establishing logical business and software/technical responsibilities between classes results in a true client/server software system in which redundancy is avoided. © SAP AG BC401 5-17 &RPSDWLELOLW\DQG'HVLJQ$LPV &RPSDWLELOLW\ $%$32EMHFWV3URJUDPP $%$32EMHFWV3URJUDPP l '$7$FRXQWHU7<3(L '$7$FRXQWHU7<3(L ZDW\SH.1$ ZDW\SH.1$ l &/$66OFOBFDU'(),1,7,21 &/$66OFOBFDU'(),1,7,21 (1'&/$66 (1'&/$66 l PDLQSURJUDP PDLQSURJUDP $%$32EMHFWVLVDWUXH FRPSDWLEOHH[WHQVLRQRI$%$3 $%$32EMHFWVVWDWHPHQWVFDQ EHXVHGLQSURFHGXUDO$%$3 SURJUDPV 2EMHFWV FODVVHV WKHPVHOYHV FRQWDLQFODVVLF$%$3 VWDWHPHQWV 'HVLJQDLPVZHUH l &5($7(2%-(&7 &5($7(2%-(&7 l FRXQWHU FRXQWHU FRXQWHU FRXQWHU 029(ZD72 029(ZD72 l $VVLPSOHDVSRVVLEOH 2QO\REMHFWRULHQWHGFRQFHSWV WKDWKDYHSURYHGXVHIXO ,QFUHDVHGXVHRIW\SHFKHFNV SAP AG 2002 n ABAP Objects is not a new language, but has been developed as an extension of ABAP. It integrates seamlessly into ABAP syntax and the ABAP programming model. All enhancements are strictly upward compatible. n In ABAP objects, types have to be assigned more strictly than in ABAP. - for example, when defining interface parameters for methods, you must type the parameters. The correct pass by value is then checked by the system when the method is called. n In ABAP Objects, the ABAP language has been cleaned up. As part of this language clean up, the system sometimes executes stricter syntax checks for previously permitted constructions and obsolete statements are not allowed. The stricter syntax checks usually result in a syntax that should also be used outside ABAP Objects, but where the old forms cannot be prohibited for compatibility reasons. For further information, refer to the ABAP Objects documentation under 5HSODFHPHQWRI2EVROHWH 6WDWHPHQWV © SAP AG BC401 5-18 $%$30DLQ0HPRU\DQG(QFDSVXODWLRQ ñ ò6 ó ôP (õriò ö P÷( Gø( ô6ø( GøG (ù ú6ò ¥¦-§N¨]©¦NªN©N« ©§N¨ P« ! "#"$ ! % l 0RGXODUL]DWLRQXQLWVIRU ½ ­y¯±° ²³(´y¯¸¾ HQFDSVXODWLQJ l :RUNLQJZLWKJOREDOGDWD RIWKHPDLQSURJUDP ñ òó ô Põhrò öP÷( Gø( ô6ø( øG (ù ú6 ò ¥*¦ §¨]©¦Nª©N«-©§¨ P« j( k( Gl (m n-o pP 6l$ Ú ØN Ù n-Ù l Ì DQGEXVLQHVV ¾ DUH HQFDSVXODWHGLQREMHFWV Ä ² Ä ½ ­y¯°²³(´y¯ þqÿhiý ûüý ü SAP AG 2002 n One feature and design aim of object-oriented languages is that business functions are held separately. n The client (in this case, the main program) uses the addresses of the objects (pointers or reference variables) to access their encapsulated functions. Amongst other things, this concept is to improve the structuring, reusability, and maintainability of the software. © SAP AG BC401 5-19 7KH6RIWZDUH'HYHORSPHQW3URFHVV 5HTXLUHPHQW LGHD tJ({xz(' & À Vu*;)J;z*)vy vy** v() |+ J}{v |,+ 7HVW ; $QDO\VLVDQG GHVLJQ ,PSOHPHQWDWLRQ $%$32EMHFWV SAP AG 2002 n In object-oriented programming, the analysis and design phase is even more important than it is for procedural programming. The reason for this is that in object-oriented programming, decisions taken during the analysis and design phase have even more pronounced effects on implementation than they do in procedural programming. © SAP AG BC401 5-20 ,QWURGXFWLRQWR2EMHFW2ULHQWHG3URJUDPPLQJ 6XPPDU\ <RXDUHQRZDEOHWR l 1DPHWKHPRVWVLJQLILFDQWGLIIHUHQFHVEHWZHHQ SURFHGXUDODQGREMHFWRULHQWHGSURJUDPPLQJ l 6WDWHWKHDLPVEHKLQGGHYHORSLQJWKH$%$3 2EMHFWVSURJUDPPLQJODQJXDJH SAP AG 2002 © SAP AG BC401 5-21 $QDO\VLVDQG'HVLJQ &RQWHQWV l &ODVVLILFDWLRQRIREMHFWV l 80/ l &ODVVGLDJUDPV l 6HTXHQFHGLDJUDPV SAP AG 2002 © SAP AG BC401 6-1 $QDO\VLVDQG'HVLJQ8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l /LVWVRPHLPSRUWDQWGLDJUDPW\SHVLQ80/ l &UHDWHDFODVVGLDJUDP l &UHDWHDVHTXHQFHGLDJUDP SAP AG 2002 © SAP AG BC401 6-2 $QDO\VLVDQG'HVLJQ,QWHJUDWLRQLQ&RXUVH&RQWHQW O K G K M-PJNQ V HH-AW G KA DSC RD O K G UK C T O H GK L +*-, , ) (' ) "!$#% D& K-L % % @BAC DEA F DG HJI M KN L H XZYB[-\+]-^U_a` ^ \ `-b ^Jc .0/-1 1 2 34 / : 57: 6+2 8 3 4 4 6 >/-9;/-? : / / 3=< 5 SAP AG 2002 © SAP AG BC401 6-3 $QDO\VLVDQG'HVLJQ &ODVVLILFDWLRQ &ODVVLILFDWLRQ 80/WKHPRGHOLQJVWDQGDUG 80/WKHPRGHOLQJVWDQGDUG SAP AG 2002 © SAP AG BC401 6-4 &ODVVLILFDWLRQRI2EMHFWV de fgihj k=gml OFOBSHRSOH OFOBYHKLFOH nporqtsuswvyx{zuqu|0}~ ~zo7}B SAP AG 2002 n In the real world, there are objects, such as various airplanes , cars, and people. Some of these objects are very similar, that is, they can be described using the same attributes or characteristics and provide the same functions. n Similar objects are grouped together in classes. Each class is described once, and each object is then created in accordance with this blueprint. A class is therefore a description of a quantity of objects characterized by the same structure and the same behavior. For example, the vehicle "make x, ... serial number xxx" is an object of the class "vehicle". This object is therefore a concrete instance of the class. © SAP AG BC401 6-5 'LIIHUHQW$EVWUDFWLRQVRID&ODVV uu7y- "¡¢ y Ü ³ ¼Ô É Åָķ´=Á OFOBYHKLFOH Ý i£ ¤a¦¨ Ý"Þ Þ Þ ß Å"¸²Ä ´7Á ß ÁÂrÃBÄ Å§ÅÖÄ Æ¬Ç ß ´µ§¶ µ§¸ ¹tº»½¼ ¾½¾¼²¿ À Á7Â"Ã7Ä Å¬ÅrÄ Æ§Ç ¯°±²° ³ ´7µ7¶·µZ¸ 0DNH 7\SH £¥¤§¦¨ 'RRUV £¥©aªa¨Z« ª¬©a©­+® :KHHOV ÐÒÑ ¨7¨Z« ® ÈÊɼ À½ËÌ Í Á=Ä ÇaÎrÏ ÓÔ ³ÖÕ ¾Ø× Õ± »É Ù§´=¸$ÚSÅÛÚ7¶Ã§Á 36 OFOBYHKLFOH Ý i£ ¤¬¦-¨ Ý"Þ Þ Þ ß Í ÁÄ Ç¬Î¬Ï ß Ù0´¸ÚÅàÛÚ¶áÃZÁ SAP AG 2002 n In this context, abstractions are a simplified representations of complex relationships in the real world. An actually existing object is abstracted to the significant dimensions that are to be mapped. Insignificant details are left out in order to aid understanding of the overall system. n This example concerns cars. Software for a car enthusiast and software for a scrap merchant contain different abstractions (classes) for these objects. n A class can contain very different objects depending on the DEVWUDFWLRQ. n While in one software system the class lcl_vehicle describes all transport vehicles (including bikes), in another system it describes all motorized machines with wheels. Both classes have the same name but describe different objects. n In our examples, the class lcl_vehicle describes all motorized vehicles with 4 wheels. © SAP AG BC401 6-6 5HSUHVHQWDWLRQRID&ODVV OFOBYHKLFOH uäJå¢ PDNH â 7rJãyB½ PRGHOO Optional, does not have to be Assoziationsme specified SULFH FRORU æ ½7çè é-ê=ëUìí îðïj ìñ"ò VHWBPDNH GLVSOD\BDWWULEXWHV LQFUHDVHBVSHHG SAP AG 2002 n UML notation: A class is represented with its name, attributes, and methods. With UML, you also have the option of omitting either the attribute or the method part. n Attributes describe the data that can be stored in the objects in a class. They define the state of an object. n Methods describe the functions that can be executed on the data of the object. They contain the executable source code and therefore also represent an object’s "behavior". n ABAP Objects events are not included in class diagrams. © SAP AG BC401 6-7 &ODVVHVDQG2EMHFWV de(ó k=eñ(eàìî-eàlôïìôí(jëUk=ñàeöõ ÷ø &ODVV *HQHUDOGHVFULSWLRQRIREMHFWV EOXHSULQW l ÞÞÞ 6SHFLILHVVWDWXVGDWD DWWULEXWHV DQGEHKDYLRU PHWKRGV l l j k ÞÞÞ 2EMHFW LQVWDQFH l « ùZ« ú0û§¨ Ѭü ù§« ¨ OFOBYHKLFOH 5HSUHVHQWDWLRQRIUHDOZRUOG j k ý+þðÿ « ù0« ú7ûZ¨ Ѭü ùa« ¨ 6SHFLILFLQVWDQFHRIDFODVV SAP AG 2002 n A FODVV is a set of objects that have the same structure and the same behavior. A class is therefore like a blueprint, in accordance with which all objects in that class are created. n Every REMHFW has an identity, a status (set of attribute values), and behavior (set of methods and events). The structure and behavior of similar objects are defined in their shared class. n Identity is an attribute that distinguishes each object from all other objects. Identity is often confused with having the same attribute values or with a unique name. 7ZRGLIIHUHQWREMHFWVFDQKDYH LGHQWLFDODWWULEXWHYDOXHVDQGVWLOOQRWEHLGHQWLFDO Example: Two coffee cups are the same height and diameter, have the same handle and are both white. Although they look exactly the same, they are still two separate cups. n In German literature on the subject of object orientation, we often speak of instances. In object orientation an instance is simply an object. Another synonym of REMHFW is LQVWDQFH. © SAP AG BC401 6-8 $QDO\VLVDQG'HVLJQ &ODVVLILFDWLRQ &ODVVLILFDWLRQ 80/WKHPRGHOLQJVWDQGDUG 80/WKHPRGHOLQJVWDQGDUG SAP AG 2002 © SAP AG BC401 6-9 0RGHOLQJZLWK80/ l 80/VWDQGVIRU8QLILHG0RGHOLQJ/DQJXDJH l ,WLVDJOREDOVWDQGDUG l ,WLVDODQJXDJHDQGIRUPRIQRWDWLRQIRUWKHVSHFLILFDWLRQ FRQVWUXFWLRQYLVXDOL]DWLRQDQGGRFXPHQWDWLRQRIPRGHOV IRUVRIWZDUHV\VWHPV 'LDJUDPW\SHV w w w w w &ODVVGLDJUDP %HKDYLRUGLDJUDPVXFKDVDVHTXHQFHGLDJUDP &RPSRQHQWGLDJUDP 'LVWULEXWLRQGLDJUDP SAP AG 2002 n UML (Unified Modeling Language) is a standardized modeling language. It is used for the specification, construction, visualization, and documentation of models for software systems and enables uniform communication between various users. UML does not describe the steps in the object-oriented development process. n UML is an industry standard and has been standardized by the OMG (Object Management Group) since September 1997 as UML Version 1.1. The members of the OMG are continuously developing it further. SAP uses UML as the company-wide standard for object-oriented modeling. n You can find the UML specifications on the OMG homepage at: http://www.omg.org n UML describes a number of different diagram types in order to represent different views of a system. &ODVVGLDJUDPV show the static view of a model. n %HKDYLRUGLDJUDPV demonstrate the relationships and method calls between objects. They emphasize the timing sequence of method calls. n Component diagrams show the organization and dependencies of components. n Distribution diagrams represent the dependencies of software and hardware. © SAP AG BC401 6-10 ([DPSOHRID&ODVV'LDJUDP OFOBUHQWDO 1 0..* OFOBERRNLQJ 0..* 1 OFOBFXVWRPHU 1 1..* OFOBYHKLFOH OFOBFDU 1 OFOBWUXFN 1..* OFOBZKHHO OFOBEXV SAP AG 2002 n n A class diagram describes the elements contained in the model and their various static relationships. There are two basic forms of static relationships: • Associations (for example, a car rental customer books a car) • Generalization / specialization (for example, a car and a bus are both vehicles) In class diagrams, classes can also be shown with their attributes and methods. © SAP AG BC401 6-11 $VVRFLDWLRQ A customer can rent several cars OFOBERRNLQJ 0..* A booking refers to a customer ERRNV ¯ ° ° ¿ ÔÕà³ ¼ ¿ Õ± ¼²ÌS¼²É * or 0..* 1 1..* 0..1 1 OFOBFXVWRPHU Association name Many Exactly one One or more Zero or one SAP AG 2002 An association describes a semantic relationship between classes. The specific relationship between objects in these classes is known as an object link. Object links are therefore the instances of an association. An association is usually a relationship between different classes. However, an association can also be recursive; in this case, the class would have a relationship with itself. In most cases, recursive associations are used to link two different objects in one class. The points below assume that the associations are binary. Each association has two roles, one for each direction of the association (booking → customer, customer → booking). Roles can have names (for example, the association car → reservation could be called "reservation"). Each role has a cardinality that shows how many instances participate in this relationship. The multiplicity is the number of participating objects in one class that have a relationship to an object in the other class. UML notation: • An association is represented by a line between the class symbols • The cardinality of the relationship can be shown at each end of the line • Associations can be given a name for ease of identification (a verb or a short text). This name is written in italics above the line and may have an arrow to show the read direction. Both are optional. © SAP AG BC401 6-12 $JJUHJDWLRQDQG&RPSRVLWLRQ $JJUHJDWLRQLVDVSHFLDO FDVHRIDVVRFLDWLRQD ZKROHSDUWUHODWLRQVKLS Aggregation symbol OFOBYHKLFOH &RPSRVLWLRQLVDVSHFLDO FDVHRIDJJUHJDWLRQDQ H[LVWHQFHGHSHQGHQW ZKROHSDUWUHODWLRQVKLS 1 0..* OFOBZKHHO Composition symbol OFOBUHQWDO 1 1..* OFOBERRNLQJ SAP AG 2002 n Aggregation is a special kind of association. Aggregation describes one object that contains another or consists of other objects (whole-part). A vehicle consists of wheels. The relationship can be described by the words "consists of" or "is a part of". n UML notation for aggregation: An aggregation, like an association, is represented by a line between two classes, which then additionally has a small rhombus at one end. The rhombus is always at the aggregate end, that is, the whole object end. Otherwise the notation conventions are the same as for associations. n Composition is a special kind of aggregation. Composition describes the fact that the object contained cannot exist without the aggregate (for example, a car reservation cannot exist without the car rental). n Differences to aggregation: The cardinality on the aggregate side can only be one. Each part is only part of one composite object, otherwise the existence dependency would be contradictory. The lifetime of the individual parts is linked to the lifetime of the aggregate: Parts are created either with or immediately after the aggregate, and they are destroyed either with or immediately before the aggregate. n UML notation for composition: Like aggregation, composition is shown as a line between two classes and marked with a small rhombus on the aggregate side. However, in contrast to aggregation, the rhombus is filled in. © SAP AG BC401 6-13 *HQHUDOL]DWLRQDQG6SHFLDOL]DWLRQ OFOBFDU OFOBWUXFN Generalization Inheritance arrow Specialization OFOBYHKLFOH OFOBFDU Specialization OFOBYHKLFOH OFOBWUXFN Generalization RU SAP AG 2002 n UML notation: Generalization and specialization are denoted by triangular arrows that point from the subordinate class to the superclass. Several arrows can be combined into a tree. © SAP AG BC401 6-14 6HTXHQFH'LDJUDPV([DPSOH OFOBGULYHU Time 3URFHVV GHVFULSWLRQ RSWLRQDO OFOBFDU 0HWKRG SDUDPHWHU Life line of object 5HWXUQYDOXH Control focus SAP AG 2002 n Sequence diagrams, unlike class diagrams, show the dynamics between objects. They are used to represent a particular process or a particular situation. Sequence diagrams focus on the time sequence of the information exchange: a) Creation and deletion of objects b) Message exchange between objects n Sequence diagrams have no notation for representing static methods. n The object life line is represented by vertical dotted lines. n The control focus is shown as a vertical rectangle on the object life line. The control focus shows the object’s "active" period: • An object is active when actions are executed • An object is indirectly active if it is waiting for a subordinate procedure to end. n Messages are shown as horizontal arrows between the object lines. The message is written above the arrow in the form PHWKRG SDUDPHWHU . There are various ways of representing the reply; in this example, the arrow is shown as a returning arrow. n You can also include a description of the process and add comments to the object life line as required. © SAP AG BC401 6-15 6HTXHQFH'LDJUDP'HOHJDWLRQ OFOBGULYHU OFOBFDU JHWBIXHOBOHYHO OFOBWDQN JHWBIXHOBOHYHO UHBOHYHO UHBOHYHO UHBOHYHO WDQN!JHWBIXHOBOHYHO UHBOHYHO IXHOIXHOBPD[ SAP AG 2002 n In delegation, two objects are involved in handling a request: The recipient of the request delegates the execution of the request to a delegate. n Example: The driver (lcl_driver) calls the method get_fuel_level for the class car (lcl_car). The car cannot carry out this task itself. Therefore, the car calls the get_fuel_level method for the class (lcl_tank), that is the car GHOHJDWHV the execution of the method to the tank. n The main advantage of delegation (as a re-use mechanism) lies in the option of changing the behavior of the recipient by substituting the delegate (at runtime). For example, delegation enables the car to be equipped with a new tank, without the call changing for the client or for the car class. n Good encapsulation often forces the use of delegation: If tank in the above example were a private attribute of the class lcl_car, the user could not address the tank directly, but only through the car. © SAP AG BC401 6-16 $QDO\VLVDQG'HVLJQ6XPPDU\ <RXDUHQRZDEOHWR l /LVWVRPHGLDJUDPW\SHVLQ80/ l &UHDWHDFODVVGLDJUDP l &UHDWHDVHTXHQFHGLDJUDP SAP AG 2002 © SAP AG BC401 6-17 ([HUFLVHV 8QLW$QDO\VLVDQG'HVLJQ 7RSLF80/&ODVV'LDJUDPV At the conclusion of these exercises, you will be able to: • Create a UML class diagram An airline needs to manage its airplanes. 1-1 Use a pencil and paper to create a UML class diagram that contains the following classes: - Airline: OFOBFDUULHU – Airplane (general): OFOBDLUSODQH – Passenger airplane: OFOBSDVVHQJHUBSODQH – Cargo plane: OFOBFDUJRBSODQH 1-1-1 Include some appropriate attributes and methods for every class. 1-1-2 Draw lines to represent the relationships between the classes and indicate possible cardinalities. © SAP AG BC401 6-18 6ROXWLRQV 8QLW$QDO\VLVDQG'HVLJQ 7RSLF80/&ODVV'LDJUDPV © SAP AG BC401 6-19 3ULQFLSOHVRI2EMHFW2ULHQWHG3URJUDPPLQJ &RQWHQWV l &ODVVHV l 2EMHFWV l $WWULEXWHV l 0HWKRGV l 9LVLELOLW\HQFDSVXODWLRQ l ,QVWDQWLDWLRQ l &RQVWUXFWRU l *DUEDJHFROOHFWRU SAP AG 2002 © SAP AG BC401 7-1 3ULQFLSOHVRI2EMHFW2ULHQWHG3URJUDPPLQJ 8QLW 2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l &UHDWHFODVVHV l &UHDWHREMHFWV l &DOOPHWKRGV l ([SODLQKRZWKHJDUEDJHFROOHFWRUZRUNV SAP AG 2002 © SAP AG BC401 7-2 3ULQFLSOHVRI2EMHFW2ULHQWHG3URJUDPPLQJ ,QWHJUDWLRQLQ&RXUVH&RQWHQW D @ = @ BEF > 8 @ 8 H: 9 G: D @ = @JI CLK >M = D > =@ 9A t ]v^ q Z [ h e q [srut c4p c _n o i [ ] c ^ n Z\[W]L^J_ ] `ba cdfehgjilkm %# $& & ' ()*,+.- ) + $/1$6 0 $ " " ! $ (324* $ 0 0 ' ( )5 : @ A : = > ? 78 9 :;4< B @ C A> 8 NOP Q RSUTWV S Q VX SY SAP AG 2002 © SAP AG BC401 7-3 3ULQFLSOHV &ODVVHVDWWULEXWHVDQGPHWKRGV &ODVVHVDWWULEXWHVDQGPHWKRGV 2EMHFWVLQVWDQFHVRIFODVVHV 2EMHFWVLQVWDQFHVRIFODVVHV $FFHVVLQJDWWULEXWHVDQGPHWKRGV $FFHVVLQJDWWULEXWHVDQGPHWKRGV 7KHFRQVWUXFWRU 7KHFRQVWUXFWRU $GGLWLRQDOSULQFLSOHV $GGLWLRQDOSULQFLSOHV SAP AG 2002 © SAP AG BC401 7-4 ([DPSOHRID&ODVV OFOBYHKLFOH 3XEOLF components 1{LUwxJz { 3ULYDWH components wyx1zW{ hsU4bUL h h wl|J}1{J~ {LUwxJz { 0HWKRGV Implementation 3ULYDWHDFFHVV •Encapsulation • Normally attributes 3XEOLFDFFHVV •Interface • Normally methods, events SAP AG 2002 n In the graphic, the public component of the class is accessed using the green node or starting point displayed on the left. A user or client can use this node to access the public components and hence also indirectly access the private components. However, the private components of the class cannot be addressed directly . They are not visible to the outside user. n Why are the private components of a class hidden? This principle is called LQIRUPDWLRQKLGLQJ or HQFDSVXODWLRQ and is used to protect the user. Let us assume that a class changes its private components, while its interface remains unchanged. Any user who simply needs to access the interface of the class can carry on working with the class as usual. The user does not notice the change. However, if an class changes its public components, then any user who accesses these public components must take these changes into account. © SAP AG BC401 7-5 'HILQLQJ&ODVVHV ±³²f±µ´·¶¹¸yºy» OFOBYHKLFOH &/$66OFOBYHKLFOH'(),1,7,21 (1'&/$66 &/$66OFOBYHKLFOH,03/(0(17$7,21 ®4¯ ~ ° x{ components components { ¡|J} ¢ £¥¤ ¦ § ¨ £ §W©ª¬«ª¢ ­© (1'&/$66 SAP AG 2002 n A FODVV is a set of objects that have the same structure and the same behavior. A class is therefore like a EOXHSULQW, in accordance with which all objects in that class are created. n The components of the class are defined in the definition part. The components are attributes, methods, events, constants, types, and implemented interfaces. Only methods are implemented in the implementation part. n The CLASS statement cannot be nested, that is, you cannot define a class within a class. © SAP AG BC401 7-6 $WWULEXWHV l $WWULEXWHVFDQKDYHDQ\NLQGRI GDWDW\SH OFOBFDU l &1,3675,1* l 'LFWLRQDU\W\SHV Public l 8VHUGHILQHGW\SHV l 7<3(5()72 GHILQHVDUHIHUHQFHWRDQ REMHFWLQWKLVFDVH³UBFDU´ Private PDNH7<3(675,1* UBPRWRU 7<3(5()72 OFOBUHQWDO ¼½b¾¿À¼ SAP AG 2002 n Attributes describe the data that can be stored in the objects of a class. n Class attributes can be of any type: n • Data types: scalar (for example data element), structured, in tables • ABAP elementary types (C, I, ...) • Object references • Interface references Examples of attributes for the class lcl_car are: • make (car make) • modell (type , model) • ser_no (serial number) • color (color) • car_type (estate, convertible, ...) • max_seats (number of seats) • r_motor (reference to class lcl_motor) • ... © SAP AG BC401 7-7 $WWULEXWHV7\SHVDQG&RQVWDQWV6\QWD[ &/$66FODVVQDPH!'(),1,7,21 7<3(6QRUPDOH7\SGHILQLWLRQ! &2167$176FRQVWDQW7<3(W\SH!9$/8(YDOXH! '$7$YDULDEOH7<3(W\SH! YDULDEOH7<3(GGLFBW\SH! YDULDEOH/,.(YDULDEOH YDULDEOH7<3(W\SH!9$/8(YDOXH! YDULDEOH7<3(W\SH!5($'21/< YDULDEOH7<3(5()72FODVVQDPH! YDULDEOH7<3(5()72LQWHUIDFH! &/$66'$7$RQO\BRQFH7<3( (1'&/$66 SAP AG 2002 n In classes, you can only use the TYPE addition to refer to data types. n You can only use the LIKE reference for local data objects. n The READ-ONLY addition means that a public attribute declared with DATA can be read from outside, but can only be changed by methods of the class. n You can currently only use the READ-ONLY addition in the public visibility section (PUBLIC SECTION) of a class declaration or in an interface definition. © SAP AG BC401 7-8 $WWULEXWHVDQG9LVLELOLW\ &/$66OFOBYHKLFOH'(),1,7,21 l 3XEOLFDWWULEXWHV &DQEHYLHZHGDQG FKDQJHGE\DOOXVHUVDQG LQDOOPHWKRGV Á 'LUHFWDFFHVV Á l 3ULYDWHDWWULEXWHV &DQRQO\EHYLHZHGDQG FKDQJHGIURPZLWKLQWKH FODVV Á Á 1RGLUHFWDFFHVV IURPRXWVLGHWKHFODVV 38%/,&6(&7,21 '$7$PDNH7<3(VWULQJ 35,9$7(6(&7,21 (1'&/$66 &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 ... 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJ (1'&/$66 SAP AG 2002 n You can protect attributes against access from outside by characterizing them as private attributes (defined in the PRIVATE SECTION). n Attributes and their values that may be used directly by an external user are public attributes and are defined in the PUBLIC SECTION. n In the above example for the class lcl_car, the attribute make is defined as a public attribute. n Public attributes belong to the LQWHUIDFH of the class, that is their implementation is publicized. If you want to hide the internal implementation from users, you must define internal and external views of attributes. n As a general rule, you should define as few public attributes as possible. © SAP AG BC401 7-9 $FFHVVLQJ3ULYDWH$WWULEXWHV ÇÉÈÊ »jËyÌ OFOBYHKLFOH 3XEOLF ÂÄÃ4Åh UÆ 3ULYDWH PDNH VHWBPDNH JHWBPDNH ... SAP AG 2002 n You can access an object’s private attributes using public methods, which in turn output this attribute or change it. n It is not possible to directly access private attributes from outside (for example, main program or other object). The only exception lies in the so-called "friend" concept, which will be dealt with later in the course. © SAP AG BC401 7-10 ,QVWDQFH$WWULEXWHVDQG6WDWLF$WWULEXWHV l ,QVWDQFHDWWULEXWHV 2QHSHULQVWDQFH Á 6WDWHPHQW'$7$ Á l 6WDWLFDWWULEXWHV 2QO\RQHSHUFODVV Á 6WDWHPHQW&/$66'$7$ Á Á $OVRNQRZQDVFODVV DWWULEXWHV &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 ... 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJ ... &/$66'$7$QBRBYHKLFOHV7<3(L (1'&/$66 SAP AG 2002 n There are two kinds of attributes: • Static attributes • Instance attributes n Instance attributes are attributes that exist separately for each object. Instance attributes are defined using the ABAP keyword DATA. n Static attributes exist only once for each class and are visible for all (runtime) instances in that class. Static attributes usually contain information that applies to all instances, such as: • Data that is the same in all instances • Administrative information about the instances in that class (for example, counters, ...) n Static attributes are defined using the CLASS-DATA keyword. n You may come across the expression "class attributes" in documentation, however, the official term in ABAP Objects (as in C++, Java) is "static" attributes. © SAP AG BC401 7-11 ,QVWDQFH$WWULEXWHVDQG6WDWLF$WWULEXWHV ,QWHUQDOVHVVLRQ Í Æv hÎ Æ hÎÀÎ WÏ v QBRBYHKLFOHV Þàß ásß â ãäásß ß åâ æ%ç,ß èé UBYHKLFOH UBYHKLFOH UBYHKLFOH Ð Ý ÒHÓ ÔÓ ÕÖLØ×ÙÚ ÔÓ Ø 6WDWLFDWWULEXWHV RQO\H[LVWRQFH Ð Ñ ÒHÓ ÔÓ Õ×ÖLØ×Ù×Ú ÔLÓ Ø ,QVWDQFHV REMHFWV Ð Û ÒJÓ ÔÓ ÕÖLØLÙÜÚ ÔÓ Ø SAP AG 2002 n The graphic shows the static attribute n_o_vehicles. It exists only once, regardless of how many instances there are of lcl_vehicle. n Therefore, you can say that instances share their common attributes. © SAP AG BC401 7-12 0HWKRGV6\QWD[ 0HWKRGVFDQKDYH DVLJQDWXUH &/$66FODVVQDPH!'(),1,7,21 0(7+2'6PHWKRGBQDPH! >,03257,1*LPBYDU!7<3(W\SH! (;3257,1*H[BYDU!7<3(W\SH! &+$1*,1*FKBYDU!7<3(W\SH! 5(7851,1*9$/8( UHBYDU! 7<3(W\SH! EXCEPTIONS <exception> 5$,6,1*FODVVBH[FHSWLRQ! @ (1'&/$66 &/$66FODVVQDPH!,03/(0(17$7,21 0(7+2'PHWKRGBQDPH! (1'0(7+2' (1'&/$66 0HWKRGVFRQWDLQWKH VRXUFHFRGHDQGKHQFH GHILQHWKHEHKDYLRURIDQ REMHFW SAP AG 2002 n Methods are internal procedures in classes that determine the behavior of an object. They can access all attributes in their class and can therefore change the state of an object. n Methods have a parameter interface (called VLJQDWXUH) that enables them to receive values when they are called and pass values back to the calling program. n In ABAP Objects, methods can have IMPORTING, EXPORTING, CHANGING, and RETURNING parameters as well as exception parameters. All parameters can be passed by value or reference. (As of SAP R/3 Basis Release 6.10, you should no longer use the EXCEPTIONS parameter for exceptions but use the RAISING addition instead; this will be discussed in more detail later.) n You can define a return code for methods using RETURNING. You can only do this for a single parameter, which additionally must be passed as a value. Also, you cannot then define EXPORTING and CHANGING parameters. You can define functional methods using the RETURNING parameter (this will be explained in more detail). n All input parameters (IMPORTING, CHANGING parameters) can be defined as optional parameters in the declaration using the OPTIONAL or DEFAULT additions. These parameters then do not necessarily have to be passed when the object is called. If you use the OPTIONAL addition, the parameter remains initialized according to type, whereas the DEFAULT addition allows you to enter a start value. © SAP AG BC401 7-13 $FFHVVLQJ3ULYDWH0HWKRGV ÇÉÈÊ »jËyÌ Â¨ÃÅu UÆ OFOBYHKLFOH 3XEOLF 3ULYDWH VHWBPDNH LQLWBPDNH PDNH êWêWê SAP AG 2002 n Methods also have to be assigned to a visibility area. This determines whether the methods can be called from outside or only from within the class. n It is not possible to directly access private methods from outside. However, a private method can be called by a public method. n Both method types can access the public and private attributes. © SAP AG BC401 7-14 0HWKRGVDQG9LVLELOLW\ l 3XEOLFPHWKRGV &DQEHFDOOHGIURP DQ\ZKHUH Á l 3ULYDWHPHWKRGV Á &DQRQO\EHFDOOHG ZLWKLQWKHFODVV SAP AG 2002 n &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6VHWBPDNHLPSRUWLQJ LPBPDNH7<3(VWULQJ 35,9$7(6(&7,21 0(7+2'6LQLWBPDNH '$7$PDNH7<3(VWULQJ (1'&/$66 &/$66OFOBYHKLFOH,03/(0(17$7,21 0(7+2'LQLWBPDNH PDNH QRPDNH (1'0(7+2' 0(7+2'VHWBPDNH ,)LPBPDNH,6,1,7,$/ &DOOLQJLQLWBPDNH (/6( PDNH LPBPDNH (1',) (1'0(7+2' (1'&/$66 In this example, init_make is a private method that is called by the public method set_make. © SAP AG BC401 7-15 ,QVWDQFH0HWKRGVDQG6WDWLF0HWKRGV 5XOHV l ,QVWDQFHPHWKRGV &DQXVHERWKVWDWLFDQGLQVWDQFHFRPSRQHQWVLQWKHLU LPSOHPHQWDWLRQSDUW Á &DQEHFDOOHGXVLQJDQLQVWDQFH Á l 6WDWLFPHWKRGV &DQRQO\XVHVWDWLFFRPSRQHQWVLQWKHLULPSOHPHQWDWLRQ SDUW Á Á &DQEHFDOOHGXVLQJWKHFODVV SAP AG 2002 n Static methods are defined at class level. They are similar to instance methods, but with the restriction that they can only use static components (such as static attributes) in the implementation part. This means that static methods do not need instances and can be called from anywhere. They are defined using the CLASS-METHODS statement, and they are bound by the same syntax and parameter rules as instance methods. n The term "class method" is common, but the official term in ABAP Objects (as in C++, Java) is "static method". © SAP AG BC401 7-16 ,QVWDQFH0HWKRGVDQG6WDWLF0HWKRGV([DPSOH &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6VHWBPDNH,03257,1*LPBPDNH7<3(VWULQJ &/$660(7+2'6JHWBFRXQW(;3257,1*H[BFRXQW7<3(L 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJ &/$66'$7$QBRBYHKLFOHV7<3(L (1'&/$66 &/$66OFOBYHKLFOH,03/(0(17$7,21 0(7+2'JHWBFRXQW H[BFRXQW QBRBYHKLFOHV (1'0(7+2' (1'&/$66 SAP AG 2002 n In the static method get_count, you can only use the static attribute n_o_vehicles. All other attributes of the class are instance attributes and can only appear in instance methods. © SAP AG BC401 7-17 6XPPDU\DQG80/1RWDWLRQ OFOBYHKLFOH PDNH PRGHO QBRBYHKLFOHV ë 3ìÜí Æ îhï u4¹ ð 3ìÜí h3vÃ4Ψ¬ hï h¹¬ ÂñÄ.ÎĬ ò4uï ubòÎ43 hh4 Æ Lh VHWBPDNH LQLWBPDNH JHWBFRXQW &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6VHWBPDNH,03257,1*LPBPDNH7<3(VWULQJ &/$660(7+2'6JHWBFRXQW(;3257,1*H[BFRXQW7<3(L 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJ &/$66'$7$QBRBYHKLFOHV7<3(L 0(7+2'6LQLWBPDNH (1'&/$66 SAP AG 2002 n A UML class diagram shows firstly the class name and, underneath that, the class attributes and methods. n The visibility of components in a class is shown in UML using the characters "+" and "-": + indicates public components indicates private components Alternatively, public and private can be prefixed to the methods. The third option for providers of modeling tools in UML is to introduce their own symbols for visibility. Representation of visibility characteristics is optional and is normally only used for models that are close to implementation. n Static components are marked with an underscore. n The method signature is represented as follows (optional): • The input and output parameters and the parameters to be changed are shown in brackets. • The return code is separated from the type name by a colon. © SAP AG BC401 7-18 3ULQFLSOHV &ODVVHVDWWULEXWHVDQGPHWKRGV &ODVVHVDWWULEXWHVDQGPHWKRGV 2EMHFWVLQVWDQFHVRIFODVVHV 2EMHFWVLQVWDQFHVRIFODVVHV $FFHVVLQJDWWULEXWHVDQGPHWKRGV $FFHVVLQJDWWULEXWHVDQGPHWKRGV 7KHFRQVWUXFWRU 7KHFRQVWUXFWRU $GGLWLRQDOSULQFLSOHV $GGLWLRQDOSULQFLSOHV SAP AG 2002 © SAP AG BC401 7-19 &UHDWLQJ2EMHFWV 5XOHV l l OFOBYHKLFOH PDNH PRGHO VHUBQR QBRBYHKLFOHV VHWBPDNH LQLWBPDNH JHWBFRXQW 2EMHFWVDUHFUHDWHGXVLQJWKH&5($7(2%-(&7 VWDWHPHQW 2EMHFWVFDQRQO\EHFUHDWHGDQGDGGUHVVHGXVLQJ UHIHUHQFHYDULDEOHV &5($7(2%-(&7UBYHKLFOH OFOBYHKLFOH Public öàþ ó¡ôõ ö ú öàþ ü ÷ þ ÿ ü ý ê êWê ó¡ôõWö Private ó¡÷øWöWùWù öWû ÷ ú üàý êWê ê SAP AG 2002 n A class contains the generic description of an object. It describes all the characteristics that are common to all objects in that class. During the program runtime, the class is used to create specific objects (instances). This process is called instantiation. n Example: The specific object “Car xy with Ser-No. 0815" is created through instantiation from the class lcl_vehicle; it is created in the main memory at runtime. The lcl_vehicle class itself does not exist as an independent runtime object in ABAP Objects. n Implementation: Objects are instantiated using the statement:CREATE OBJECT. During instantiation, the runtime environment dynamically requests main memory space and assigns it to the object. © SAP AG BC401 7-20 5HIHUHQFH9DULDEOHV &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 35,9$7(6(&7,21 (1'&/$66 :KDWGRWKHVH UHIHUHQFHYDULDEOHV SRLQWWR" &/$66OFOBYHKLFOH,03/(0(17$7,21 (1'&/$66 '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH UBYHKLFOH7<3(5()72OFOBYHKLOFH '()*+*(, )* - " " !"#$&% ... SAP AG 2002 n DATA: r_vehicle1 TYPE REF TO lcl_vehicle declares a reference variable that acts as a pointer to an object. © SAP AG BC401 7-21 &UHDWLQJ2EMHFWV6\QWD[ '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH UBYHKLFOH7<3(5()72OFOBYHKLFOH &5($7(2%-(&7UBYHKLFOH &5($7(2%-(&7UBYHKLFOH 021435 65 789":; 65 9 Public . Private */, 02<435 6"5 789:; 65 9 ()*+* - Public Private SAP AG 2002 n The CREATE OBJECT statement creates an object in the main memory. The attribute values of this object are either initial values or correspond to the VALUE entry. n Reference variables can also be assigned to each other. For the above example this would mean that r_vehicle1 and r_vehicle2 point to the same object. © SAP AG BC401 7-22 *DUEDJH&ROOHFWRU '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH UBYHKLFOH7<3(5()72OFOBYHKLFOH &5($7(2%-(&7UBYHKLFOH &5($7(2%-(&7UBYHKLFOH 021435 65 789":; 65 9 UBYHKLFOH UBYHKLFOH Public Private (+)**(, 02<435 6"5 789:; 65 9 '()*+*- Public Private SAP AG 2002 n As soon as no more references point to an object, the Garbage Collector removes it from the memory. n The Garbage Collector is a system routine that automatically deletes objects that can no longer be addressed from the main memory and releases the memory space they occupied. © SAP AG BC401 7-23 *DUEDJH&ROOHFWRU3URFHGXUH l l l $OOLQGHSHQGHQWUHIHUHQFHVLQWKHJOREDOPDLQPHPRU\DUHFKHFNHG7KH UHIHUHQFHVSRLQWWRDFWLYHREMHFWVZKLFKDUHPDUNHGLQWHUQDOO\ 5HIHUHQFHVRIFODVVRULQVWDQFHDWWULEXWHVWRRWKHUREMHFWVDUHIROORZHG 7KHVHREMHFWVDUHDOVRPDUNHG 2EMHFWVWKDWDUHQRWPDUNHGDUHGHOHWHGIURPWKHPDLQPHPRU\ 02<435 6"5 7?@BAC9F6D I /J+K 02=>3/5 65 7+? @BAC96ED 0*GH3/5 6"5 7?@BAC9F6D SAP AG 2002 n Independent references are references that have not been defined within a class. © SAP AG BC401 7-24 %XIIHULQJ5HIHUHQFHV '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH LWDE7<3(7$%/(2)5()72OFOBYHKLFOH &5($7(2%-(&7UBYHKLFOH $33(1'UBYHKLFOH72LWDE 02=>3/5 65 7+? @BAC96ED &5($7(2%-(&7UBYHKLFOH $33(1'UBYHKLFOH72LWDE 021L3/5 6"5 7+? @BAC9F6MD /223$7LWDE,172UBYHKLFOH ZRUNZLWKWKHFXUUHQWLQVWDQFH (1'/223 ... SAP AG 2002 n If you want to keep several objects from the same class in your program, you can define an internal table, which, for example, only consist of one column containing the object references for this class. n You can process the objects using a LOOP through the internal table. © SAP AG BC401 7-25 $JJUHJDWLRQ([DPSOH OFOBYHKLFOH Public 0SRETU3/5 65 7VW:F9F95 Private þ%ô4O ööù N ú üFPQ 02=G43/5 65 7VX:F9F9"5 02=YH35 65 7VZ:F9M9+5 021"[\35 65 7"VW:F9M9+5 SAP AG 2002 n If a class defines object references to a second class as attributes (in the above example: References to objects of the class lcl_wheel), only these object references will be stored in an object belonging to that class. n The objects in the second class lcl_wheel have their own identity. They are encapsulated in the first class lcl_vehicle and can only be addressed from this class using reference variables. © SAP AG BC401 7-26 3ULQFLSOHV &ODVVHVDWWULEXWHVDQGPHWKRGV &ODVVHVDWWULEXWHVDQGPHWKRGV 2EMHFWVLQVWDQFHVRIFODVVHV 2EMHFWVLQVWDQFHVRIFODVVHV $FFHVVLQJDWWULEXWHVDQGPHWKRGV $FFHVVLQJDWWULEXWHVDQGPHWKRGV 7KHFRQVWUXFWRU 7KHFRQVWUXFWRU $GGLWLRQDOSULQFLSOHV $GGLWLRQDOSULQFLSOHV SAP AG 2002 © SAP AG BC401 7-27 &DOOLQJ0HWKRGV ]_^U`Uacbed OFOBYHKLFOH Public Private PRWRUBRQ UBYHKLFOH!PRWRUBRQ 0HWKRG 5HIHUHQFH &RPSRQHQWVHOHFWRU SAP AG 2002 n Every object behaves in a certain way. This behavior is determined by its methods. There are three types of method: é 1. Methods that trigger the behavior and do not return values (see example) é 2. Methods that return a value é 3. Methods that return or change several values n An object that requires the services of another object sends a message to the object providing the services. This message names the operation to be executed. The implementation of this operation is known as a method. n For the sake of simplicity, method will henceforth be used as a synonym for operation and message. n The example shows the new syntax for method calls, in which the CALL-METHOD prefix is omitted. © SAP AG BC401 7-28 &DOOLQJ,QVWDQFH0HWKRGV6\QWD[ f*g)h Jji g lkmJn o)K h+p &$//0(7+2'LQVWDQFH!!LQVWDQFHBPHWKRG! (;3257,1*LPBYDU! YDULDEOH! ,03257,1*H[BYDU! YDULDEOH! &+$1*,1*FKBYDU! YDULDEOH! 5(&(,9,1*UHBYDU! YDULDEOH! EXCEPTIONS <exception> = <nr> q o)MJr g K g osJ2i/J2*o g i h o)t u vxw+y p VHHRQOLQHGRFXPHQWDWLRQ LQVWDQFH!!LQVWDQFHBPHWKRG! >DGGLWLRQV@ '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH '$7$PDNHBQDPH7<3(675,1* ... PDNHBQDPH WKHPDNHRIWKHFDU &$//0(7+2'UBYHKLFOH!VHWBPDNH(;3257,1*LPBPDNH PDNHBQDPH RWKHUYDULDQWVLQFHDYDLODEOHVHHGRFXPHQWDWLRQ UBYHKLFOH!VHWBPDNH PDNHBQDPH QRZJHWWLQJVRPHWKLQJEDFNIURPPHWKRG UBYHKLFOH!JHWBPDNH ,03257,1*H[BPDNH PDNHBQDPH SAP AG 2002 n Instance methods are called using CALL METHOD <reference>-><instance_method>. n Since SAP R/3 Basis Release 6.10, the shortened form is also supported; CALL METHOD is omitted. For further information, refer to the online documentation. n Special case: When calling an instance method from within another instance method, you can omit the instance name. The method is automatically executed for the current object. n For the method call set_make, you can omit the EXPORTING addition in the brackets. In this case, it is sufficient to set the actual parameter of the caller (in the example: make_name). However, if the method has two or more parameters in its interface, all actual and formal parameters within the brackets must have the EXPORTING addition. n In the case of methods that return parameters to the caller, the IMPORTING addition must always be used and all actual and formal parameters must be listed. n In method calls, multiple parameters are separated by spaces. © SAP AG BC401 7-29 &DOOLQJ6WDWLF0HWKRGV6\QWD[ 6WDWLFPHWKRGV&$//0(7+2'FODVVQDPH! !FODVVBPHWKRG! >DGGLWLRQV@ FODVVQDPH! !FODVVBPHWKRG! >DGGLWLRQV@ '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH '$7$PDNHBQDPH7<3(675,1* FRXQW7<3(, ... JHWBFRXQWKDVRQHLQWHUIDFHSDUDPHWHUUHBFRXQW &$//0(7+2'OFOBYHKLFOH !JHWBFRXQW ,03257,1*UHBFRXQW FRXQW RWKHUYDULDQWVLQFHDYDLODEOHVHHGRFXPHQWDWLRQ OFOBYHKLFOH !JHWBFRXQW ,03257,1*UHBFRXQW FRXQW SAP AG 2002 n Static methods (also referred to as class methods) are called using CALL METHOD <classname>=><class_method>. n Static methods are addressed with their class name, since they do not need instances. n Note: If you are calling a static method from within the class, you can omit the class name. © SAP AG BC401 7-30 )XQFWLRQDO0HWKRGV ikm l D E )XQFWLRQDOPHWKRG z|{~}} 's's~ 2QO\RQH5(7851,1*SDUDPHWHU l 2QO\,03257,1*SDUDPHWHUVDQGH[FHSWLRQVDUHSRVVLEOH z|{~} .'se D 5(&(,9,1*SDUDPHWHUVSRVVLEOH E 9DULRXVIRUPVRIGLUHFWFDOOSRVVLEOH w w w 029(&$6(/223 /RJLFDOH[SUHVVLRQV ,)(/6(,):+,/(&+(&.:$,7 $ULWKPHWLFH[SUHVVLRQVDQGELWH[SUHVVLRQV &20387( VHHH[DPSOHD EF SAP AG 2002 n Methods that have a RETURNING parameter are described as functional methods. These methods cannot have EXPORTING or CHANGING parameters, but has many (or as few) IMPORTING parameters and exceptions as required. n Functional methods can be used directly in various expressions: • Logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT) • The CASE statement (CASE, WHEN) • The LOOP statement • Arithmetic expressions (COMPUTE) • Bit expressions (COMPUTE) • The MOVE statement. © SAP AG BC401 7-31 )XQFWLRQDO0HWKRGV([DPSOH &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6JHWBDYHUDJHBIXHO ,03257,1*LPBGLVWDQFH7<3(VBGLVWDQFH LPBIXHO 7<3(W\BIXHO 5(7851,1*9$/8( UHBIXHO 7<3(W\BIXHO (1'&/$66 '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH UBYHKLFOH7<3(5()72OFOBYHKLFOH DYJBIXHO7<3(W\BIXHO ... H[DPSOHIRUVKRUWV\QWD[LQDULWPHWRSHUDWLRQ DYJBIXHO UBYHKLFOH!JHWBDYHUDJHBIXHO LPBGLVWDQFH LPBIXHO UBYHKLFOH!JHWBDYHUDJHBIXHO LPBGLVWDQFH LPBIXHO SAP AG 2002 n n Depending on the number of IMPORTING parameters, the syntax for functional methods is as follows (same for static functional methods): • No IMPORTING parameters: ref->func_method( • Exactly 1 IMPORTING parameter: ref->func_method( p1 ) or ref->func_method( im_1 = p1 ) • Several IMPORTING parameters: p2 ) ref->func_method( im_1 = p1 im_2 = ) Example of detailed syntax for functional method call: CALL METHOD r_vehicle->get_average_fuel EXPORTING im_distance = 500 im_fuel = 50 RECEIVING re_fuel = avg_fuel. Here, re_fuel is the formal parameter of the interface and avg_fuel is the actual parameter of the calling program. © SAP AG BC401 7-32 ([WHUQDO$FFHVVWR3XEOLF$WWULEXWHV &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 '$7$PDNH7<3(VWULQJ5($'21/<“just a demo &/$66'$7$QBRBYHKLFOHV7<3(L5($'21/<“just a demo (1'&/$66 OFOBYHKLFOH '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH '$7$PDNHBQDPH7<3(VWULQJ FRXQW7<3(L PDNH 67$572)6(/(&7,21 * PDLQSURJUDPWKLQNRIDFOLHQW & &5($7(2%-(&7UBYHKLFOH }{s } PDNHBQDPH UBYHKLFOH!PDNH³RQO\LISXEOLFDWWU FRXQW OFOBYHKLFOH !QBRBYHKLFOHV³RQO\LISXEOLFDWWU SAP AG 2002 There are different ways of accessing public attributes from outside the class: n You access static attributes using <classname> !<class_attribute> n You access instance attributes using <instance>!<instance_attribute> n ! and ! are the component selectors © SAP AG BC401 7-33 3ULQFLSOHV &ODVVHVDWWULEXWHVDQGPHWKRGV &ODVVHVDWWULEXWHVDQGPHWKRGV 2EMHFWVLQVWDQFHVRIFODVVHV 2EMHFWVLQVWDQFHVRIFODVVHV $FFHVVLQJDWWULEXWHVDQGPHWKRGV $FFHVVLQJDWWULEXWHVDQGPHWKRGV 7KHFRQVWUXFWRU 7KHFRQVWUXFWRU $GGLWLRQDOSULQFLSOHV $GGLWLRQDOSULQFLSOHV SAP AG 2002 © SAP AG BC401 7-34 &RQVWUXFWRU l l l 6SHFLDOPHWKRGIRUFUHDWLQJ REMHFWVZLWKGHILQHGLQLWLDOVWDWH 2QO\KDV,03257,1* SDUDPHWHUVDQG(;&(37,216 ,VH[HFXWHGRQO\RQFHSHU LQVWDQFH OFOBYHKLFOH PDNH PRGHO QBRBYHKLFOHV FRQVWUXFWRU &5($7(2%-(&7 021435 6"5 789:; 6"5 9 Public Private 0(7+2'6FRQVWUXFWRU,03257,1*LPBSDUDPHWHU! (;&(37,216H[FHSWLRQ! SAP AG 2002 n n The constructor is a special instance method in a class with the name constructor. The following rules apply: • Each class can have one constructor. • The constructor is automatically called at runtime within the CREATE OBJECT statement. • If you need to implement the constructor, then you must define and implement it in the PUBLIC SECTION. When exceptions are raised in the constructor, instances are QRW created, so no main memory space is occupied. © SAP AG BC401 7-35 &RQVWUXFWRU([DPSOH &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*LPBPDNH7<3(VWULQJ LPBPRGHO7<3(VWULQJ 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJZHLJKW7<3(S &/$66'$7$QBRBYHKLFOHV7<3(L (1'&/$66 &/$66OFOBYHKLFOH,03/(0(17$7,21 0(7+2'FRQVWUXFWRU PDNH LPBPDNH PRGHO LPBPRGHO $''72QBRBYHKLFOHV (1'0(7+2' (1'&/$66 2 m/2* )nH)2)¡ ¢*¢ '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH &5($7(2%-(&7UBYHKLFOH (;3257,1*LPBPDNH )HUUDUL LPBPRGHO ) &DOOIURPWKH PDLQSURJUDP SAP AG 2002 n n You need to implement the constructor when, for example: • You need to allocate (external) resources • You need to initialize attributes that cannot be covered by the VALUE addition to the DATA statement • You need to modify static attributes You cannot normally call the constructor explicitly. © SAP AG BC401 7-36 3UHYLHZ6WDWLF&RQVWUXFWRU &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 &/$660(7+2'6&/$66B&216758&725 35,9$7(6(&7,21 &/$66'$7$QBRBYHKLFOHV7<3(, (1'&/$66 &/$66OFOBYHKLFOH,03/(0(17$7,21 0(7+2'&/$66B&216758&725 ... (1'0(7+2'... (1'&/$66 l l l 6SHFLDOVWDWLFPHWKRG $XWRPDWLFDOO\FDOOHGEHIRUH WKHFODVVLVILUVWDFFHVVHG 2QO\H[HFXWHGRQFHSHU SURJUDP 6WDWLF&RQVWUXFWRULVFDOOHGEHIRUHIROORZLQJVWDWHPHQWV GHPR &5($7(2%-(&7UBYHKLFOH GHPR FRXQWHU OFOBYHKLFOH !QBRBYHKLFOHV³LIDWWULEXWHLVSXEOLF GHPR OFOBYHKLFOH !JHWBFRXQW LPSRUWLQJUHBFRXQW FRXQWHU SAP AG 2002 n n The static constructor is a special static method in a class with the name class_constructor. It is executed precisely once per program. The static constructor of a class <classname> is called automatically when the class is first accessed, but before any of the following actions are executed: Creating an instance in the class using CREATE OBJECT <obj>, where <obj> has the data type REF TO <classname> • Addressing a static attribute using <classname>=><attribute> • Calling a static attribute using CALL METHOD <classname>=><classmethod> • Registering a static event handler method using SET HANDLER <classname>=><handler_method> FOR <obj> • Registering an event handler method for a static event in class <classname>. The static constructor cannot be called explicitly. © SAP AG BC401 7-37 3ULQFLSOHV &ODVVHVDWWULEXWHVDQGPHWKRGV &ODVVHVDWWULEXWHVDQGPHWKRGV 2EMHFWVLQVWDQFHVRIFODVVHV 2EMHFWVLQVWDQFHVRIFODVVHV $FFHVVLQJDWWULEXWHVDQGPHWKRGV $FFHVVLQJDWWULEXWHVDQGPHWKRGV 7KHFRQVWUXFWRU 7KHFRQVWUXFWRU $GGLWLRQDOSULQFLSOHV $GGLWLRQDOSULQFLSOHV SAP AG 2002 © SAP AG BC401 7-38 1DPHVSDFH:LWKLQD&ODVV OFOBYHKLFOH l 7KHVDPHQDPHVSDFHIRU $WWULEXWHV £ ¤º»¼r¦ ½ components 0HWKRGV £ 0HWKRG PDNH (YHQWV £ 7\SHV £ &RQVWDQWV £ £ ¤¥S¦ §¨E©ª components $WWULEXWH PDNH ªE©­¬®¯ ° ±³²E« ´ µ±µ¶L·n¸L·C° ¹F¶ $/,$6QDPHV l 7KHUHLVDORFDOQDPHVSDFHZLWKLQ PHWKRGV SAP AG 2002 n Within a class, attribute names, method names, event names, constant names, type names and alias names all share the same namespace. n There is a local namespace within methods. Definitions of local variables can cover components in one class. © SAP AG BC401 7-39 7KH5HIHUHQFH9DULDEOH0( &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU ,03257,1*LPBPDNH7<3(VWULQJ LPBPRGHOO7<3(VWULQJ 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJ... (1'&/$66 &/$66OFOBYHKLFOH,03/(0(17$7,21 0(7+2'FRQVWUXFWRU³just a demo '$7$PDNH7<3(VWULQJ9$/8( %HQ] &21&$7(1$7(LPBPDNHPDNH,1720(!PDNH (1'0(7+2' OFOBYHKLFOH ¤º»+¼r¦ ½ components ¤¥S¦ §¨E©'ª components $WWULEXWH PDNH ªE©­¬®¯ ° ±³²E« ´ µ±µ¶L·n¸L·'° ¹¶ 0(!PDNH 0(7+2''800< * calling own methods from inside class * call method display_attributes( ) * with the short syntax variant: GLVSOD\BDWWULEXWHV (1'0(7+2' (1'&/$66 SAP AG 2002 n You can address the object itself within instance methods using the implicitly available reference variable me. n Description of example: In the constructor, the instance attribute make is covered by the locally defined variable make. In order to still be able to address the instance attribute, you need to use me. n The dummy method demonstrates how to call a class’s own method. You can omit the prefix me->. n Other important use: An object calls another object’s method and passes its own address. © SAP AG BC401 7-40 3ULQFLSOHVRI2EMHFW2ULHQWHG3URJUDPPLQJ8QLW 6XPPDU\ <RXDUHQRZDEOHWR l &UHDWHFODVVHV l &UHDWHREMHFWV l &DOOPHWKRGV l ([SODLQKRZWKHJDUEDJHFROOHFWRUZRUNV SAP AG 2002 © SAP AG BC401 7-41 ([HUFLVHV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF &UHDWLQJD&ODVV At the conclusion of these exercises, you will be able to: • Create a local class An airline needs to manage its airplanes. 0RGHOVROXWLRQ 6$3%&B$,56B0$,1B$ 6$3%&B$,56B$include program 1-1 1-2 1-3 Create the package =%&B(where ##: is your group number) and save all the repository objects you have created during the course in this package. Create the main program =%&BB0$,1B$,53/$1( and the include program =%&BB$,53/$1( the main program contains (##: group number). Create the class OFOBDLUSODQHin the include program. 1-3-1 This class has two SULYDWHLQVWDQFHDWWULEXWHV: - QDPH - SODQHW\SH. The attribute for the airplane name should be of the type STRING. Define the attribute for the plane type using the table field VDSODQHSODQHW\SH. 1-3-2 The class has a SULYDWHVWDWLFDWWULEXWH: - QBRBDLUSODQHV. This attribute should be type I. © SAP AG BC401 7-42 1-3-3 The class has a SXEOLFLQVWDQFHPHWKRG VHWBDWWULEXWHV to set the private instance attributes name and plane type. Enter two corresponding importing parameters for the declaration of the method in the definition part. The definition of these parameters should be analogous to the two attributes. Implement the method in the implementation part; set both attributes. Each time the method is called, the static attribute QBRBDLUSODQHV should increase by one. (This is actually not right but will be corrected later). 1-3-4 The class is to have another SXEOLFLQVWDQFHPHWKRG GLVSOD\BDWWULEXWHV to display the instance attributes. Declare this method and, in the implementation part, output the attributes using the WRITE statement (you can also display the icon icon_ws_plane, in which case you must add TYPE-POOLS icon to the program. 1-3-5 Declare and implement a SXEOLFVWDWLFPHWKRG GLVSOD\BQBRBDLUSODQHV to display the static attribute QBRBDLUSODQHV. (In the remaining exercises in this course, you can always start with the program you created in the previous exercise or copy the corresponding model solution and continue working with this program.) © SAP AG BC401 7-43 ([HUFLVHV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF ,QVWDQWLDWLQJ2EMHFWV At the conclusion of these exercises, you will be able to: • Instantiate objects 0RGHOVROXWLRQ 6$3%&B$,56B0$,1B% 6$3%&B$,56B$include program 2-1 Create a reference to the class OFOBDLUSODQH. 2-2 Define an internal table for buffering objects of the class OFOBDLUSODQH. The type of the internal table should therefore be 5()72OFOBDLUSODQH. 2-3 Create several objects of the class OFOBDLUSODQH and store them in the internal table. 2-4 Follow the program flow in the Debugger. (In the remaining exercises in this course, you can always start with the program you created in the previous exercise or copy the corresponding model solution and continue working with this program.) © SAP AG BC401 7-44 ([HUFLVHV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF 0HWKRG&DOOV At the conclusion of these exercises, you will be able to: • Call instance methods and static methods 0RGHOVROXWLRQ 6$3%&B$,56B0$,1B& 6$3%&B$,56B&include program 3-1 Call the static method GLVSOD\BQBRBDLUSODQHV (before instantiating an object in class OFOBDLUSODQH). 3-2 Use the VHWBDWWULEXWHVmethod to set the attributes for all objects already created. Choose an airplane name and airplane type and pass them as text literals. (For the plane type you can use a type from the table SAPLANE, for example “747-400”.) 3-3 Display the object attributes using the GLVSOD\BDWWULEXWHV method. 3-4 Call the static method GLVSOD\BQBRBDLUSODQHV a second time. 3-5 Add a functional static method gHWBQBRBDLUSODQHV to the class OFOBDLUSODQH.The method must be public and have the UHBFRXQW (type I) return parameter (no input parameters). 3-6 Test your functional method by calling it from the main program. © SAP AG BC401 7-45 ([HUFLVHV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF &RQVWUXFWRU At the conclusion of these exercises, you will be able to: • Create a constructor for a class • Create an object using the constructor 0RGHOVROXWLRQ 6$3%&B$,56B0$,1B' 6$3%&B$,56B'include program 4-1 Create a FRQVWUXFWRU for the class OFOBDLUSODQH(in your include program =%&BB$,53/$1() The simplest way of doing this is to copy the method VHWBDWWULEXWHV, which you now no longer need. 4-1-1 4-1-2 The constructor must have two importing parameters that fill the instance attributes QDPHand SODQHW\SH. The static attribute QBRBDLUSODQHV should have an ascending sequence of one in the constructor. 4-2 In the method VHWBDWWULEXWHV, comment out the line in which the static attribute QBRBDLUSODQHV is increased by one (if you still want to use this method). 4-3 In the main program =%&BB0$,1B$,53/$1(, extend the creation of the object with the constructor interface. Fill the constructor’s interface parameters with the same values you used when calling the VHWBDWWULEXWHVmethod. 4-4 2SWLRQDO Comment out the method call VHWBDWWULEXWHV or delete the call. © SAP AG BC401 7-46 ([HUFLVHV 8QLW3ULQFLSOHVRI2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF&DOOLQJD3ULYDWH0HWKRG At the conclusion of these exercises, you will be able to: • Call methods within a class 0RGHOVROXWLRQ 6$3%&B$,56B0$,1B( 6$3%&B$,56B(include program 5 Create the SULYDWHPHWKRG JHWBWHFKQLFDOBDWWULEXWHV for the class OFOBDLUSODQH(in your include program =%&BB$,53/$1(). 5-1 The airplane type is the import parameter. (Type saplane-planetype) 5-2 The export parameter is the weight WEIGHT and the tank capacity TANKCAP. Refer to the types in the table SAPLANE. 5-3 The result, both export parameters are ascertained in a database access to the table SAPLANE. Therefore, both attributes are read, depending on the airplane type. 5-4 If the imported plane type does not exist in the table, set default values (weight 100000, tank capacity 10000). 5-5 Test your method JHWBWHFKQLFDOBDWWULEXWHV: © SAP AG 5-5-1 By calling it from the main program 5-5-2 By calling it within the GLVSOD\BDWWULEXWHV method 5-3-3 Which call was successful, and why? BC401 7-47 6ROXWLRQV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF &UHDWLQJD&ODVV *&---------------------------------------------------------------------* *& Report SAPBC401_AIRS_MAIN_a * *&---------------------------------------------------------------------* 5(3257VDSEFBDLUVBPDLQBD 7<3(322/6LFRQ ,1&/8'(6$3%&BDLUVB$ *&-----------------------------------------------------------------* *& Include SAPBC401_AIRS_A * *&-----------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* &/$66OFOBDLUSODQH'(),1,7,21 38%/,&6(&7,21 &2167$176SRVB7<3(L9$/8( 0(7+2'6VHWBDWWULEXWHV,03257,1* LPBQDPH7<3(VWULQJ LPBSODQHW\SH7<3(VDSODQHSODQHW\SH GLVSOD\BDWWULEXWHV &/$660(7+2'6GLVSOD\BQBRBDLUSODQHV 35,9$7(6(&7,21 '$7$QDPH7<3(VWULQJ SODQHW\SH7<3(VDSODQHSODQHW\SH &/$66'$7$QBRBDLUSODQHV7<3(L © SAP AG BC401 7-48 (1'&/$66 *------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *------------------------------------------------------------------* &/$66OFOBDLUSODQH,03/(0(17$7,21 0(7+2'VHWBDWWULEXWHV QDPH LPBQDPH SODQHW\SH LPBSODQHW\SH QBRBDLUSODQHV QBRBDLUSODQHV (1'0(7+2' 0(7+2'GLVSOD\BDWWULEXWHV :5,7(LFRQBZVBSODQHDVLFRQ 1DPHRIDLUSODQH $LUSODQHW\SH (1'0(7+2' $7SRVBQDPH $7SRVBSODQHW\SH 0(7+2'GLVSOD\BQBRBDLUSODQHV :5,7( 7RWDOQXPEHURISODQHV FD $7SRVBQBRBDLUSODQHV/()7-867,),(' (1'0(7+2' (1'&/$66 © SAP AG BC401 7-49 6ROXWLRQV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF ,QVWDQWLDWLQJ2EMHFWV *&---------------------------------------------------------------------* *& Report SAPBC401_AIRS_MAIN_b * *&---------------------------------------------------------------------* *& create and insert planes into internal table * *&---------------------------------------------------------------------* REPORT sapbc401_airs_main_b. TYPE-POOLS icon. INCLUDE SAPBC401_airs_A. '$7$UBSODQH7<3(5()72OFOBDLUSODQH SODQHBOLVW7<3(7$%/(2)5()72OFOBDLUSODQH START-OF-SELECTION. *############################## &5($7(2%-(&7UBSODQH $33(1'UBSODQH72SODQHBOLVW &5($7(2%-(&7UBSODQH $33(1'UBSODQH72SODQHBOLVW &5($7(2%-(&7UBSODQH $33(1'UBSODQH72SODQHBOLVW © SAP AG BC401 7-50 6ROXWLRQV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF 0HWKRG&DOOV *&---------------------------------------------------------------------* *& Report SAPBC401_AIRS_MAIN_C * *&---------------------------------------------------------------------* *& call method set_Attributes to initialize objects * *& and visualize content of objects via display_attributes * *&---------------------------------------------------------------------* REPORT sapbc401_airs_main_c. TYPE-POOLS icon. INCLUDE sapbc401_airs_c. '$7$UBSODQH7<3(5()72OFOBDLUSODQH SODQHBOLVW7<3(7$%/(2)5()72OFOBDLUSODQH FRXQWW\SHL START-OF-SELECTION. *############################## OFOBDLUSODQH !GLVSOD\BQBRBDLUSODQHV &5($7(2%-(&7UBSODQH $33(1'UBSODQH72SODQHBOLVW UBSODQH!VHWBDWWULEXWHV LPBQDPH /+%HUOLQ LPBSODQHW\SH &5($7(2%-(&7UBSODQH $33(1'UBSODQH72SODQHBOLVW UBSODQH!VHWBDWWULEXWHV LPBQDPH $$1HZ<RUN LPBSODQHW\SH /223$7SODQHBOLVW,172UBSODQH UBSODQH!GLVSOD\BDWWULEXWHV (1'/223 © SAP AG BC401 7-51 OFOBDLUSODQH !GLVSOD\BQBRBDLUSODQHV FDOOLQJWKHIXQFWLRQDOPHWKRGJHWBQBRBDLUSODQHV ORQJV\QWD[IRUIXQFWLRQDOFDOO OFOBDLUSODQH !JHWBQBRBDLUSODQHV UHFHLYLQJUHBFRXQW FRXQW VKRUWV\QWD[IRUIXQFWLRQDOFDOO FRXQW OFOBDLUSODQH !JHWBQBRBDLUSODQHV ZULWH 1XPEHURIDLUSODQHV FRXQW *&---------------------------------------------------------------------* *& Include SAPBC401_AIRS_C * *& Develops functional static method get_n_o_airplanes * *&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* &/$66OFOBDLUSODQH'(),1,7,21 38%/,&6(&7,21 &2167$176SRVB7<3(L9$/8( 0(7+2'6VHWBDWWULEXWHV,03257,1* LPBQDPH7<3(VWULQJ LPBSODQHW\SH7<3(VDSODQHSODQHW\SH GLVSOD\BDWWULEXWHV &/$660(7+2'6GLVSOD\BQBRBDLUSODQHV JHWBQBRBDLUSODQHVUHWXUQLQJ9$/8( UHBFRXQW W\SH, 35,9$7(6(&7,21 '$7$QDPH7<3(VWULQJ SODQHW\SH7<3(VDSODQHSODQHW\SH &/$66'$7$QBRBDLUSODQHV7<3(L (1'&/$66 © SAP AG BC401 7-52 *------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *------------------------------------------------------------------* &/$66OFOBDLUSODQH,03/(0(17$7,21 0(7+2'VHWBDWWULEXWHV QDPH LPBQDPH SODQHW\SH LPBSODQHW\SH QBRBDLUSODQHV QBRBDLUSODQHV (1'0(7+2' 0(7+2'GLVSOD\BDWWULEXWHV :5,7(LFRQBZVBSODQHDVLFRQ 1DPHRIDLUSODQH $LUSODQHW\SH (1'0(7+2' $7SRVBQDPH $7SRVBSODQHW\SH 0(7+2'GLVSOD\BQBRBDLUSODQHV :5,7( 7RWDOQXPEHURISODQHV FD $7SRVBQBRBDLUSODQHV/()7-867,),(' (1'0(7+2' PHWKRGJHWBQBRBDLUSODQHV UHBFRXQW QBRBDLUSODQHV HQGPHWKRG (1'&/$66 © SAP AG BC401 7-53 6ROXWLRQV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF &RQVWUXFWRU *&---------------------------------------------------------------------* *& Report SAPBC401_AIRS_MAIN_d * *&---------------------------------------------------------------------* *& call constructor of class lcl_airplane * *&---------------------------------------------------------------------* REPORT sapbc401_airs_main_d. TYPE-POOLS icon. INCLUDE sapbc401_airs_d. '$7$UBSODQH7<3(5()72OFOBDLUSODQH SODQHBOLVW7<3(7$%/(2)5()72OFOBDLUSODQH START-OF-SELECTION. *############################## lcl_airplane=>display_n_o_airplanes( ). &5($7(2%-(&7UBSODQHH[SRUWLQJLPBQDPH /+%HUOLQ LPBSODQHW\SH APPEND r_plane TO plane_list. &5($7(2%-(&7UBSODQHH[SRUWLQJLPBQDPH $$1HZ<RUN LPBSODQHW\SH LOOP AT plane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. lcl_airplane=>display_n_o_airplanes( ). © SAP AG BC401 7-54 *&---------------------------------------------------------------------* *& Include SAPBC401_AIRS_d * *&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. 0(7+2'6FRQVWUXFWRU,03257,1* LPBQDPH7<3(VWULQJ LPBSODQHW\SH7<3(VDSODQHSODQHW\SH GLVSOD\BDWWULEXWHV CLASS-METHODS: display_n_o_airplanes. PRIVATE SECTION. "---------------------------------DATA: name TYPE string, planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS. *------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. 0(7+2'FRQVWUXFWRU QDPH LPBQDPH SODQHW\SH LPBSODQHW\SH QBRBDLUSODQHV QBRBDLUSODQHV (1'0(7+2' METHOD display_attributes. WRITE: / icon_ws_plane as icon, / ’Name of airplane’(001), AT pos_1 name, / ’Airplane type: ’(002), AT pos_1 planetype. ENDMETHOD. METHOD display_n_o_airplanes. © SAP AG BC401 7-55 WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD. ENDCLASS. © SAP AG BC401 7-56 6ROXWLRQV 8QLW 3ULQFLSOHVRI2EMHFW2ULHQWHG 3URJUDPPLQJ 7RSLF &DOOLQJD3ULYDWH0HWKRG *&---------------------------------------------------------------------* *& Report SAPBC401_AIRS_MAIN_e * *& * *&---------------------------------------------------------------------* *& inside display_attributes a private method is called to get * *& further details on technical aspects of the planetype * *&---------------------------------------------------------------------* REPORT sapbc401_airs_main_e. TYPE-POOLS icon. INCLUDE sapbc401_airs_e. DATA: r_plane TYPE REF TO lcl_airplane, plane_list TYPE TABLE OF REF TO lcl_airplane. START-OF-SELECTION. *############################## lcl_airplane=>display_n_o_airplanes( ). CREATE OBJECT r_plane exporting im_name = ’LH Berlin’ im_planetype = ’747-400’. APPEND r_plane TO plane_list. r_plane->display_attributes( ). CREATE OBJECT r_plane exporting im_name = ’AA New York’ im_planetype = ’727-200’. r_plane->display_attributes( ). lcl_airplane=>display_n_o_airplanes( ). © SAP AG BC401 7-57 *&---------------------------------------------------------------------* *& Include SAPBC401_AIRS_e * *&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes. PRIVATE SECTION. "---------------------------------0(7+2'6JHWBWHFKQLFDOBDWWULEXWHV ,03257,1*LPBW\SHW\SHVDSODQHSODQHW\SH (;3257,1*H[BZHLJKW7<3(VBSODQBZHL H[BWDQNFDS7<3(VBFDSDFLW\ DATA: name TYPE string, planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS. © SAP AG "lcl_airplane DEFINITION BC401 7-58 *------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. name = im_name. planetype = im_planetype. n_o_airplanes = n_o_airplanes + 1. ENDMETHOD. "constructor METHOD display_attributes. data: weight type saplane-weight, cap type saplane-tankcap. WRITE: / icon_ws_plane AS ICON, / ’Name of airplane’(001), AT pos_1 name, / ’Airplane type: ’(002), AT pos_1 planetype. get_technical_attributes( exporting im_type = planetype importing ex_weight = weight ex_tankcap = cap ). write: / ’wheight: ’(003), weight, ’tankcap: ’(004), 60 cap. ENDMETHOD. "display_attributes METHOD display_n_o_airplanes. WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD. "display_n_o_airplanes 0(7+2'JHWBWHFKQLFDOBDWWULEXWHV 6(/(&76,1*/(ZHLJKWWDQNFDS)520VDSODQH ,172 H[BZHLJKWH[BWDQNFDS :+(5(SODQHW\SH LPBW\SH ,)V\VXEUF! H[BZHLJKW H[BWDQNFDS (1',) (1'0(7+2'JHWBWHFKQLFDOBDWWULEXWHV ENDCLASS. © SAP AG "lcl_airplane IMPLEMENTATION BC401 7-59 ,QKHULWDQFH &RQWHQWV l *HQHUDOL]DWLRQVSHFLDOL]DWLRQRIFODVVHV SAP AG 2002 © SAP AG BC401 8-1 ,QKHULWDQFH8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 'HILQHDQLQKHULWDQFHUHODWLRQVKLSEHWZHHQ FODVVHV l 5HGHILQHPHWKRGV SAP AG 2002 © SAP AG BC401 8-2 ,QKHULWDQFH,QWHJUDWLRQLQ&RXUVH&RQWHQW G C ? C EHBI @ 8 C 8 ; : J; G C ? CLK FNM @O ? G @ ?C :D rNsut2vwix y z s|{ v ]^ \] b ^ l b n [ \ eo \ pq q o _ l m b g ] 4 ` a d b L c 4 e 4 f i g k h j [.\] ^_ # # " ! 798 : ;<>= ;? @BA ; CD E C F D@ 8 $&%' ' ( )*,+.-/ * - %02%6 1 % % )43 + % 1 1 ( ) *,5 P.Q9R ST U2VXW U S W Y UBZ SAP AG 2002 © SAP AG BC401 8-3 ,QKHULWDQFH80/([DPSOH OFOBYHKLFOH LVD UHODWLRQVKLS OFOBFDU FDUBW\SH PD[BVHDWV DFFHOHUWLRQ JHWBW\SH PDNH PRGHOO VHUBQR FRORU QBRBYHKLFOHV FRQVWUXFWRU GLVSOD\BDWWULEXWHV JHWBFRXQW OFOBWUXFN PD[BFDUJR QBRBWDQNV QBRBZKHHOV JHWBFDUJR OFOBEXV PD[BSDVVHQJHUV ODYDWRU\ WHOHYLVLRQ JHWBSDVVHQJHUV SAP AG 2002 n Inheritance is a relationship, in which one class (the subclass) inherits all the main characteristics of another class (the superclass). The subclass can also add new components (attributes, methods, and so on) and replace inherited methods with its own implementations. n Inheritance is an implementation relationship that emphasizes similarities between classes. In the example above, the similarities between the car, bus, and truck classes are extracted to the vehicle superclass. This means that common components are only defined/implemented in the superclass and are automatically present in the subclasses. n The inheritance relationship is often described as an "is a" relationship: A truck LVD vehicle. © SAP AG BC401 8-4 OFOBVXSHU Generalization 0XOWLSOH,QKHULWDQFH" OFOBVXSHU OFOBVXE OFOBVXE OFOBVXE Specialization } ~ u NNuu4u> SAP AG 2002 n Inheritance should be used to implement generalization and specialization relationships. A superclass is a JHQHUDOL]DWLRQof its subclasses. The subclass in turn is a VSHFLDOL]DWLRQ of its superclasses. n The situation in which a class, for example lcl_sub2, inherits from two classes (lcl_super1 and lcl_super2) simultaneously, is known as multiple inheritance. However, this is QRW implemented in ABAP Objects. ABAP Objects only has single inheritance. You can, however, simulate multiple inheritance in ABAP Objects using interfaces (see the section on interfaces). n Single inheritance does not mean that the inheritance tree only has one level. On the contrary, the direct superclass of one class can in turn be the subclass of a further superclass. In other words: The inheritance tree can have any number of levels, so that a class can inherit from several superclasses, as long as it only has one direct superclass. n Inheritance is a "one-sided relationship": Subclasses know their direct superclasses, but (super)classes do not know their subclasses. © SAP AG BC401 8-5 5HODWLRQVKLSV%HWZHHQ6XSHUFODVVHVDQG6XEFODVVHV l &RPPRQFRPSRQHQWVRQO\H[LVWRQFHLQWKH VXSHUFODVV 1HZFRPSRQHQWVLQWKHVXSHUFODVVDUH DXWRPDWLFDOO\DYDLODEOHLQVXEFODVVHV OFOBVXSHU $PRXQWRIQHZFRGLQJLVUHGXFHG SURJUDPPLQJE\GLIIHUHQFH l 6XEFODVVHVDUHH[WUHPHO\GHSHQGHQWRQ VXSHUFODVVHV :KLWH%R[5HXVH 6XEFODVVPXVWSRVVHVVGHWDLOHGNQRZOHGJHRI WKHLPSOHPHQWDWLRQRIWKHVXSHUFODVV OFOBVXE 1HZ FRPSRQHQWV ,QKHULWHG FRPSRQHQWV SAP AG 2002 n If inheritance is used properly, it provides a significantly better structure, as FRPPRQFRPSRQHQWV RQO\QHHGWREHVWRUHGRQFHFHQWUDOO\ (in the superclass) and are then automatically available to subclasses. Subclasses also benefit from modifications (however, they can also be invalidated as a result). n Inheritance provides very strong links between the superclass and the subclass. The subclass must possess detailed knowledge of the implementation of the superclass, particularly for redefinition, but also in order to use inherited components. Even if the superclass does not technically know its subclasses, the subclass often makes additional requirements of the superclass, for example, because a subclass needs certain protected components or because implementation details in the superclass need to be changed in the subclass in order to redefine methods. The basic reason is that the developer of a (super)class cannot normally predict all the requirements that subclasses will later need to make of the superclass. © SAP AG BC401 8-6 ,QKHULWDQFH6\QWD[ &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6HVWLPDWHBIXHO ,03257,1*LPBGLVWDQFH7<3(VBGLVWDQFH 5(7851,1*9$/8( UHBIXHO 7<3(W\BIXHO 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJ ... (1'&/$66 &/$66OFOBWUXFN'(),1,7,21,1+(5,7,1*)520OFOBYHKLFOH 38%/,&6(&7,21 0(7+2'6JHWBFDUJR5(7851,1*9$/8( UHBFDUJR 7<3(W\BFDUJR 35,9$7(6(&7,21 '$7$PD[BFDUJR7<3(W\BFDUJR (1'&/$66 SAP AG 2002 n Normally the only other entry required for subclasses is what has changed in relation to the direct superclass. Only DGGLWLRQV are permitted in ABAP Objects, that is, in a subclass you can "never take something away from a superclass". All components from the superclass are automatically present in the subclass. n The attributes of the superclass lcl_vehicle exist in the subclass lcl_truck; the method estimate_fuel is also available in the subclass. n The subclass defines a method get_cargo. It is not visible in the superclass. © SAP AG BC401 8-7 5HGHILQLQJ0HWKRGV &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6HVWLPDWHBIXHO ,03257,1*LPBGLVWDQFH7<3(W\BGLVWDQFH 5(7851,1*9$/8( UHBIXHO 7<3(W\BIXHO (1'&/$66 &/$66OFOBWUXFN'(),1,7,21,1+(5,7,1*)520OFOBYHKLFOH 38%/,&6(&7,21 0(7+2'6HVWLPDWHBIXHO5('(),1,7,21 (1'&/$66 &/$66OFOBWUXFN,03/(0(17$7,21 0(7+2'HVWLPDWHBIXHO VXSHU!HVWLPDWHBIXHO (1'0(7+2' (1'&/$66 $OZD\VSRLQWVWRWKH VXSHUFODVVFRPSRQHQW &DQQRWFKDQJH WKHLQWHUIDFH 1HZ LPSOHPHQWDWLRQRI PHWKRG SAP AG 2002 n The REDEFINITION statement for the inherited method must be in the same SECTION as the definition of the original method. (It can therefore not be in the PRIVATE SECTION, since a class’s private methods are not visible and therefore cannot be redefined in subclasses). n If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method. The reason for this is that ABAP Objects does not support overloading. n In the case of redefined methods, changing the interface (RYHUORDGLQJ) is not permitted; exception: Overloading is possible with the constructor. n Within the redefined method, you can access components of the direct superclass using the SUPER reference. n To implement a redefined method in a subclass, you often need to call the method of the same name in the LPPHGLDWH superclass. In ABAP Objects you can call the method from the superclass using the pseudo-reference super: The pseudo-reference super can only be used in redefined methods. © SAP AG BC401 8-8 ,QKHULWDQFHDQG5HGHILQLQJWKH&RQVWUXFWRU &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1* LPBPDNH7<3(VWULQJ (1'&/$66 &/$66OFOBYHKLFOH,03/(0(17$7,21 0(7+2'&216758&725 PDNH LPBPDNH (1'0(7+2' (1'&/$66 &/$66OFOBWUXFN'(),1,7,21,1+(5,7,1*)520OFOBYHKLFOH 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*LPBPDNH7<3(VWULQJ LPBFDUJR7<3(W\BFDUJR 35,9$7(6(&7,21 '$7$PD[BFDUJR7<3(W\BFDUJR (1'&/$66 &DQFKDQJHWKH LQWHUIDFH &/$66OFOBWUXFN,03/(0(17$7,21 0(7+2'FRQVWUXFWRU &$//0(7+2'VXSHU!FRQVWUXFWRU LPBPDNH LPBPDNH PD[BFDUJR LPBFDUJR (1'0(7+2' &DOOFRQVWUXFWRURILPPHGLDWH (1'&/$66 VXSHUFODVV SAP AG 2002 n The constructor of the superclass PXVW be called within the constructor of the subclass. The reason for this is the special function of the constructor: To ensure that objects are initialized correctly. Only the class itself, however, can initialize its own (private) components correctly; this task cannot be carried out by the subclass. Therefore it is essential that all (instance) constructors are called in an inheritance hierarchy (in the correct sequence). n For static constructors, unlike instance constructors, the static constructor in the superclass is called automatically, that is the runtime system automatically ensures that the static constructors of all its superclasses have already been executed before the static constructor in a particular class is executed. © SAP AG BC401 8-9 5XOHVIRU&DOOLQJWKH&RQVWUXFWRU OFOB '$7$UB7<3(5()72OFOB UB7<3(5()72OFOB &5($7(2%-(&7UB(;3257,1*LPBD a1 constructor (im_a1:i) &5($7(2%-(&7UB(;3257,1*LPBD LPBD l &ODVVRILQVWDQFHWREHFUHDWHG FRQVWUXFWRU ⇒)LOOLWVSDUDPHWHUV l &ODVVRILQVWDQFHWREHFUHDWHG ¡ FRQVWUXFWRU ⇒6HDUFKIRUWKHQH[WVXSHUFODVVZLWKDFRQVWUXFWRU LQWKHLQKHULWDQFHWUHH ⇒)LOOLWVSDUDPHWHUV OFOB OFOB a2 constructor (im_a1, im_a2) SAP AG 2002 n The model described for instance constructors must also be taken into account for CREATE OBJECT. n There are two main methods of creating an instance of a class using CREATE OBJECT: • 1. The class has a defined (and implemented) instance constructor In this case, when you are using CREATE OBJECT, the parameters have to be filled according to the constructor interface, that is, optional parameters may, and non-optional parameters must be filled with actual parameters. If the constructor does not have any (formal) parameters, no parameters may or can be filled. • 2. The instance constructor for that class has not been defined In this case, you must search the inheritance hierarchy for the next highest superclass in which the instance constructor has been defined and implemented. Then, when you are using CREATE OBJECT, the parameters of that class must be filled (similarly to the first method above). If there is no superclass with a defined instance constructor, then no parameters may or can be filled. n If no instance constructor has been defined for a class, then a GHIDXOWFRQVWUXFWRUZKLFKLV LPSOLFLWO\ DOZD\VSUHVHQWis used. This default constructor calls the constructor from the immediate superclass. © SAP AG BC401 8-10 ,QKHULWDQFHDQG9LVLELOLW\ l 3XEOLFFRPSRQHQWV 3527(&7('6(&7,21 '$7$WDQN7<3(5()72OFOBWDQN 'LUHFWDFFHVV ¢ 3URWHFWHGFRPSRQHQWV 2QO\YLVLEOHZLWKLQWKHFODVV DQGLWVVXEFODVVHV ¢ l 38%/,&6(&7,21... 9LVLEOHWRDOO ¢ l &/$66OFOBYHKLFOH'(),1,7,21 3ULYDWHFRPSRQHQWV ¢ ¢ 35,9$7(6(&7,21 '$7$PDNH7<3(VWULQJ (1'&/$66 2QO\YLVLEOHZLWKLQWKHFODVV 1RDFFHVVIURPRXWVLGHWKH FODVV QRWHYHQIURPWKHVXEFODVV OFOBYHKLFOH PDNH PRGHOO WDQN ... FRQVWUXFWRU GLVSOD\BDWWULEXWHV JHWBFRXQW £ ¤uNN ¥ ~ ¦,§>¨ © ªN«|¬ SAP AG 2002 n Inheritance provides an extension of the visibility concept: There are protected components. The visibility of these components lies between that of the public components (visible to all users, all subclasses, and the class itself), and private (visible only to the class itself). Protected components are visible to and can be used by all subclasses and the class itself. n Subclasses cannot access the private components (particularly attributes) of the superclass. Private components are genuinely private. This is particularly important if a (super)class needs to make local enhancements to handle errors: It can use private components to do this without knowing or invalidating subclasses. n In ABAP Objects, you must keep to the section sequence PUBLIC, PROTECTED, PRIVATE. © SAP AG BC401 8-11 9LVLELOLW\RI3URWHFWHG&RPSRQHQWV &DQEHDGGUHVVHG IURPRXWVLGHIRU DOOFOLHQWV OFOBEXV Public ,QKHULWHG Private JHWBPDNH VHWBPDNH JHWBFRXQW GLVSOD\BDWWULEXWHV HVWLPDWHBIXHO Protected ,QKHULWHG WDQN &DQRQO\EH DGGUHVVHGZLWKLQ WKHFODVV SAP AG 2002 n In this example, lcl_bus, a subclass of lcl_vehicle, can directly access the protected attribute tank. If the attribute was private, the subclasses would only be able to access tank using nonprivate methods. © SAP AG BC401 8-12 5XOHVIRU5HGHILQLQJ0HWKRGV l ,QKHULWHGPHWKRGVFDQEHUHGHILQHGLQVXEFODVVHV 5HGHILQHGPHWKRGVPXVWEHUHLPSOHPHQWHGLQVXEFODVVHV ¢ 7KHVLJQDWXUHRIUHGHILQHGPHWKRGVFDQQRWEHFKDQJHG ¢ ¢ ¢ 6WDWLFPHWKRGVFDQQRWEHUHGHILQHG ,QLQKHULWDQFHVWDWLFFRPSRQHQWVDUHVKDUHG $FODVVVKDUHVLWVQRQSULYDWHVWDWLFDWWULEXWHVZLWKDOOLWVVXEFODVVHV OFOBYHKLFOHV HVWLPDWHBIXHO OFOBFDU ¹»º¼¾½4¿»À¼¹ÁLÂ&ÃX¹iÄ OFOBWUXFN ¹»º¾¼¾½¿À¼9¹Á2Â&Ãi¹Ä OFOBEXV ¹»º¾¼¾½¿»À¼.¹4ÁLÂ.Ãi¹Ä ­ u®¯ ~ ¨N°±N²¯,³>,¨N´¨uNµµd,|>¶·,¸,° SAP AG 2002 n In ABAP Objects, you can not only add new components, but also provide inherited methods with new implementations. This is known as UHGHILQLWLRQ. You can only redefine (public and protected) instance methods, other components (static methods, attributes and so on) cannot be redefined. Changes to method parameters (signature changes) are not possible. n In UML, the redefinition of a method is represented by listing the method again in the subclass. Methods (and all other components) that are inherited but not redefined are not listed in the subclass, as their existence there is clear from the specialization relationship. n You should not confuse redefinition with "overloading". The latter describes the ability of a class to have methods with the same name but a different signature. This is not available in ABAP Objects. n There is only one static event per roll area. In this way, a class that defines a public or protected static attribute shares this attribute with all its subclasses. The significant point here is that subclasses do not each receive their own copy of the static attribute. © SAP AG BC401 8-13 5HGHILQLQJ0HWKRGV([DPSOH OFOBEXV OFOBWUXFN PD[BSDVVHQJHUV ... PD[BFDUJR ... FRQVWUXFWRU HVWLPDWHBIXHO FRQVWUXFWRU HVWLPDWHBIXHO 0(7+2'HVWLPDWHBIXHO '$7$WRWDOBZHLJKW * just an example! WRWDOBZHLJKW PD[BSDVVHQJHUV DYHUDJHBZHLJKWZHLJKW UHBIXHO WRWDOBZHLJKW LPBGLVWDQFH IDFWRU (1'0(7+2' 0(7+2'HVWLPDWHBIXHO '$7$WRWDOBZHLJKW * just an example! WRWDOBZHLJKW PD[BFDUJR ZHLJKW UHBIXHO WRWDOBZHLJKW LPBGLVWDQFH IDFWRU (1'0(7+2' SAP AG 2002 n In the above example, both redefined methods calculate the return code in different ways. The important point is that the semantics stay the same. © SAP AG BC401 8-14 ,QKHULWDQFH8QLW6XPPDU\ <RXDUHQRZDEOHWR l 'HILQHDQLQKHULWDQFHUHODWLRQVKLSEHWZHHQ FODVVHV l 5HGHILQHPHWKRGV SAP AG 2002 © SAP AG BC401 8-15 ,QKHULWDQFH([HUFLVHV 8QLW,QKHULWDQFH 7RSLF&UHDWLQJ&ODVV+LHUDUFKLHV At the conclusion of these exercises, you will be able to: • Define subclasses • Redefine superclass methods in subclasses 0RGHOVROXWLRQ 6$3%&B,1+6B0$,1B$ 6$3%&B,1+6B$include program <RXUSURJUDP =%&BB0$,1B$,53/$1( =%&BB$,53/$1(include program 1-1 Make both instance attributes of the class OFOBDLUSODQH visible to their subclasses (PRIVATE SECTION -> PROTECTED SECTION). 1-2 Create the subclass OFOBSDVVHQJHUBSODQH for the class OFOBDLUSODQH. Also, create this subclass in your include program. 1-2-1 The class is to have a private instance attribute PD[BVHDWV with the same type as table field VIOLJKWVHDWVPD[. 1-2-2 A public constructor is to be defined and implemented in the class. This constructor provides DOO instance attributes in the class with values. 1-2-3 Redefine the method GLVSOD\BDWWULEXWHVof the class OFOBDLUSODQH, so that, using the redefined method, the WRITE statement displays DOO instance attributes. 1-3 Create the subclass OFOBFDUJRBSODQH for the class OFOBDLUSODQH. Also, create this subclass in your include program. 1-3-1 The class is to have a private instance attribute PD[BFDUJR with the same type as the table field VFSODQHFDUJRPD[. 1-3-2 A public constructor is to be defined and implemented in the class. This constructor provides DOO instance attributes in the class with values. 1-3-3 Redefine the method GLVSOD\BDWWULEXWHVof the class OFOBDLUSODQH, so that, using the redefined method, the WRITE statement displays DOO instance attributes. © SAP AG BC401 8-16 1-4 Switch to your main program. 1-4-1 Use the DATA statement to create a reference for each subclass (OFOBSDVVHQJHUBSODQH, OFOBFDUJRBSODQH). 1-4-2 Call the static method GLVSOD\BQBRBDLUSODQHV (before instantiating any objects). 1-4-3 Use the two references to create one instance each of the subclasses OFOBSDVVHQJHUBSODQH and OFOBFDUJRBSODQH. Decide for yourself how to fill the attributes. 1-4-4 Call the GLVSOD\BDWWULEXWHVmethod for both instances. 1-4-5 Call the static method GLVSOD\BQBRBDLUSODQHV a second time. 1-5 Follow the program flow in the Debugger, paying special attention to the call of GLVSOD\BDWWULEXWHV. 1-6 Can the method JHWBWHFKQLFDOBDWWULEXWHVbe called directly from the redefined methodGLVSOD\BDWULEXWHV of the subclass? 1-7 Is it necessary for the subclasses to directly access the attributes QDPHand SODQHW\SH of the superclass to initialize them? Or, to formulate it differently: If these attributes remained in the private visibility area of the superclass, how would the subclasses have to access the attributes? © SAP AG BC401 8-17 ,QKHULWDQFH6ROXWLRQV 8QLW ,QKHULWDQFH 7RSLF &UHDWLQJ&ODVV+LHUDUFKLHV *&---------------------------------------------------------------------* *& Report SAPBC401_INHS_MAIN_a * *&---------------------------------------------------------------------* *& the classes lcl_passenger_plane and lcl_cargo_plane are * *& instantiated. Inheritance is shown * *&---------------------------------------------------------------------* REPORT sapbc401_inhs_main_a. INCLUDE <icon>. INCLUDE sapbc401_inhs_a. '$7$UBSODQH7<3(5()72OFOBDLUSODQH UBFDUJRW\SHUHIWROFOBFDUJRBSODQH UBSDVVHQJHUW\SHUHIWROFOBSDVVHQJHUBSODQH SODQHBOLVW7<3(7$%/(2)5()72OFOBDLUSODQH START-OF-SELECTION. *############################## lcl_airplane=>display_n_o_airplanes( ). &5($7(2%-(&7UBSDVVHQJHU(;3257,1* LPBQDPH /+%(5/,1 LPBSODQHW\SH LPBVHDWV &5($7(2%-(&7UBFDUJR(;3257,1* LPBQDPH 86+(UFXOHV LPBSODQHW\SH LPBFDUJR UBFDUJR!GLVSOD\BDWWULEXWHV UBSDVVHQJHU!GLVSOD\BDWWULEXWHV lcl_airplane=>display_n_o_airplanes( ). © SAP AG BC401 8-18 *&---------------------------------------------------------------------* *& Include SAPBC401_INHS_a * *&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* *... *---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION *---------------------------------------------------------------------* * *---------------------------------------------------------------------* &/$66OFOBFDUJRBSODQH'(),1,7,21,1+(5,7,1*)520OFOBDLUSODQH 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*LPBQDPH7<3(VWULQJ LPBSODQHW\SH7<3(VDSODQHSODQHW\SH LPBFDUJR7<3(VFSODQHFDUJRPD[ 0(7+2'6GLVSOD\BDWWULEXWHV5('(),1,7,21 35,9$7(6(&7,21 '$7$PD[BFDUJR7<3(VFSODQHFDUJRPD[ (1'&/$66OFOBFDUJRBSODQH'(),1,7,21 © SAP AG BC401 8-19 *---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION *---------------------------------------------------------------------* * *---------------------------------------------------------------------* &/$66OFOBFDUJRBSODQH,03/(0(17$7,21 0(7+2'FRQVWUXFWRU &$//0(7+2'VXSHU!FRQVWUXFWRU LPBQDPH LPBQDPH LPBSODQHW\SH LPBSODQHW\SH PD[BFDUJR LPBFDUJR (1'0(7+2'FRQVWUXFWRU 0(7+2'GLVSOD\BDWWULEXWHV VXSHU!GLVSOD\BDWWULEXWHV :5,7( 0D[&DUJR PD[BFDUJR 8/,1( (1'0(7+2'GLVSOD\BDWWULEXWHV (1'&/$66OFOBFDUJRBSODQH,03/(0(17$7,21 *---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION *---------------------------------------------------------------------* * *---------------------------------------------------------------------* &/$66OFOBSDVVHQJHUBSODQH'(),1,7,21,1+(5,7,1*)520OFOBDLUSODQH 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*LPBQDPH7<3(VWULQJ LPBSODQHW\SH7<3(VDSODQHSODQHW\SH LPBVHDWV7<3(VIOLJKWVHDWVPD[ 0(7+2'6GLVSOD\BDWWULEXWHV5('(),1,7,21 35,9$7(6(&7,21 '$7$PD[BVHDWV7<3(VIOLJKWVHDWVPD[ (1'&/$66OFOBSDVVHQJHUBSODQH'(),1,7,21 © SAP AG BC401 8-20 *---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION *---------------------------------------------------------------------* * *---------------------------------------------------------------------* &/$66OFOBSDVVHQJHUBSODQH,03/(0(17$7,21 0(7+2'FRQVWUXFWRU &$//0(7+2'VXSHU!FRQVWUXFWRU LPBQDPH LPBQDPH LPBSODQHW\SH LPBSODQHW\SH PD[BVHDWV LPBVHDWV (1'0(7+2'FRQVWUXFWRU 0(7+2'GLVSOD\BDWWULEXWHV VXSHU!GLVSOD\BDWWULEXWHV :5,7( 0D[6HDWV PD[BVHDWV 8/,1( (1'0(7+2'GLVSOD\BDWWULEXWHV ENDCLASS. © SAP AG "lcl_passenger_plane IMPLEMENTATION BC401 8-21 &DVWLQJ &RQWHQWV l &DVW l 3RO\PRUSKLVP SAP AG 2002 © SAP AG BC401 9-1 &DVWLQJ8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 8VHFDVWV l 'HYHORSJHQHULFSURJUDPVXVLQJSRO\PRUSKLVP ZLWKLQKHULWDQFH SAP AG 2002 © SAP AG BC401 9-2 &DVWLQJ,QWHJUDWLRQLQ&RXUVH&RQWHQW E A > A CFG ? 9 A 9 ; : H; E A > AJI DLK ?M > E ? >A :B rtsuUv/wLx3y p ]+q a [ \ j n ] ^ a o \] m [\ a ] j al Z [ c m [ no Z[\ ]^ \ _+` a b3c5d5egfih a ^j k e $ $ ! #" 89 : ;+<#= ;+> ?@ ; AB C A D B? 9 % &' ' ( )+*-,/.0 * . &132 & )54 , & 2 2 ( ) *-6 &7 & NOP Q RSUTWV S Q V X S Y SAP AG 2002 © SAP AG BC401 9-3 &DVWLQJ 1DUURZLQJFDVW 1DUURZLQJFDVW :LGHQLQJFDVW :LGHQLQJFDVW ,QKHULWDQFHDQGSRO\PRUSKLVP ,QKHULWDQFHDQGSRO\PRUSKLVP SAP AG 2002 © SAP AG BC401 9-4 3ULQFLSOHRI1DUURZLQJ&DVW '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH UBWUXFN7<3(5()72OFOBWUXFN OFOBWUXFN &5($7(2%-(&7UBWUXFN Public z|{~}z5 *HHUEW JHWBPDNH JHWBFRXQW z{UL#L 5HGHILQLHUW GLVSOD\BDWWULEXWHV VHWBDWWULEXWHV HVWLPDWHBIXHO 1DUURZLQJ&DVW UBYHKLFOH UBWUXFN JHWBFDUJR z{UL#L SAP AG 2002 n After the narrowing cast, you can use the r_vehicle reference to access the components of the truck instance that were inherited from lcl_vehicle - obviously, in some cases with the limitations entailed by their visibility. You can no longer access the truck-specific part of the instance (get_cargo in the above example) using the r_vehicle reference. © SAP AG BC401 9-5 &RPSDWLELOLW\DQG1DUURZLQJ&DVW l l l ,QVWDQFHVIURPVXEFODVVHVFDQEHXVHGLQDQ\FRQWH[WLQZKLFKWKH LQVWDQFHVRIWKHVXSHUFODVVDSSHDU 7KHFRPSRQHQWVLQKHULWHGIURPWKHVXSHUFODVVFDQEHDGGUHVVHG *HQHULFDFFHVVE\WKHFOLHQWLVSRVVLEOH '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH UBWUXFN7<3(5()72OFOBWUXFN OHYHO7<3(W\BOHYHO JHQHULFDFFHVVWRVXEFODVVVHUYLFHV OHYHO UBWUXFN!HVWLPDWHBIXHO 1DUURZLQJ&DVW UBYHKLFOH UBWUXFN 8VHRIWKHVXEFODVVLQVWDQFHLQWKHVXSHUFODVVFRQWH[W OHYHO UBYHKLFOH!HVWLPDWHBIXHO SAP AG 2002 n One of the significant principles of inheritance is that an instance from a subclass can be used in any context, in which an instance from the superclass appears. This is possible because the subclass has inherited DOO components from the superclass and therefore has the same interface as the superclass. The user can therefore address the subclass instance in the same way as the superclass instance. n Variables that point to a superclass instance can also refer to subclass instances at runtime. n The assignment of a subclass instance to a reference variable of the type "reference to superclass" is described as a narrowing cast, because you are switching from a more detailed view to a one with less detail. n The description "up-cast" is also used. n What is a narrowing cast used for? A user who is not interested in the finer points of cars, trucks, and busses (but only, for example, in the fuel consumption and tank gauge) does not need to know about them. This user only wants and needs to work with (references to) the lcl_vehicle class. However, in order to allow the user to work with cars, busses, or trucks, you generally need a narrowing cast. © SAP AG BC401 9-6 *HQHULF$FFHVV" OFOBUHQWDO 1 1..* OFOBYHKLFOHV 7KHFOLHQW OFOBWUXFN OFOBEXV OFOBUHQWDO Public Private LWDE i | + i i + i i i SAP AG 2002 n A possible client (car rental company for example) wants to access the list of vehicles with identically-named services. The client wishes to, for example, calculate the required amount of fuel. The client is not concerned with the details of how the car, bus, or truck do this. © SAP AG BC401 9-7 3UHSDUDWLRQVIRU*HQHULF$FFHVV OFOBUHQWDO 7KHFOLHQW Public i L Private ¡¢£g¤¦¥J¤ ¢§¨ DGGBYHKLFOH i i i ... 0(7+2'6DGGBYHKLFOH,03257,1*LPBYHKLFOH7<3(5()72OFOBYHKLFOH ... SAP AG 2002 n Objects from different classes (lcl_bus, lcl_truck, and lcl_car in the above example ) can be stored in an internal table consisting of references to the superclass (lcl_vehicle in the above example),and then processed in a uniform manner using the same access technique. n A client, the car rental company in this example, can then generically access the identically-named service of the different classes. (This will be discussed in more detail.) © SAP AG BC401 9-8 3UHSDUDWLRQVIRU*HQHULF$FFHVV &/$66OFOBUHQWDO'(),1,7,21 38%/,&6(&7,21 0(7+2'6DGGBYHKLFOH,03257,1*LPBYHKLFOH7<3(5()72OFOBYHKLFOH 0(7+2'6FDOFBHVWLPDWHGBIXHO5(7851,1*9$/8( UHBIXHO ... 3527(&7('6(&7,21 '$7$YHKLFOHBOLVW7<3(7$%/(2)5()72OFOBYHKLFOH (1'&/$66 &/$66OFOBUHQWDO,03/(0(17$7,21 0(7+2'DGGBYHKLFOH $33(1'LPBYHKLFOH72YHKLFOHBOLVW (1'0(7+2' 0(7+2'FDOFBHVWLPDWHGBIXHO '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH /223$7YHKLFOHBOLVW,172UBYHKLFOH UHBIXHO UHBIXHOUBYHKLFOH!HVWLPDWHBIXHO LPBGLVWDQFH (1'/223 (1'0(7+2' (1'&/$66 . SAP AG 2002 When objects from different classes react differently to the same method call, this is known as SRO\PRUSKLVP. To do this, the classes implement the same method in different ways. This can be done using inheritance, by redefining a method from the superclass in subclasses and implementing it differently. (,QWHUIDFHV will be discussed later; they too can enable polymorphic behavior.) n When an instance receives a message to execute a particular method, then that method is executed if it has been implemented by the class the instance belongs to. If the class has not implemented that method, but only inherited and not redefined it, then a search up through the inheritance hierarchy is carried out until an implementation of that method is found. n The dynamic type, not the static type of the reference variable is used to search for the implementation of a method (will be discussed later). r_vehicle->estimate_fuel above therefore uses the class of the instance that r_vehicle actually refers to to search for the implementation of estimate_fuel. The static type for r_vehicle, which is always REF TO lcl_vehicle is not used. n Polymorphism is one of the main strengths of inheritance: The user can work in the same way with different classes, regardless of their implementation. The search for the right implementation of a method is carried out by the runtime system, not the user. © SAP AG BC401 9-9 3RO\PRUSKLVP*HQHULF$FFHVV 0(7+2'FDOFBHVWLPDWHGBIXHO '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH /223$7YHKLFOHBOLVWLQWRUBYHKLFOH UHBIXHO UHBIXHOUBYHKLFOH!HVWLPDWHBIXHO LPBGLVWDQFH (1'/223 (1'0(7+2' © ª«-¬ ­¬ ®¯°i±/­ ² Public ¡¢£g¤¦¥J¤ ¢§¨ ³i´i´iµ·¶+¸¹ µ´iº´i»¼¾½¼L´Lµ¸ ¿ÀiÁÂà ÄÁLÅ·ÆÇLÈÅ|É © Ê«¬ ­¬ ®Ë ±Ì Public i³ ´i´iµ·¶+¸-¹ µ´iº´i»¼¾½ ¼L´Lµ¸ ¿ÀiÁ|Âà ÄÁLÅ·ÆÇLÈÅ|É 0(7+2'HVWLPDWHBIXHO... WRWDOBZHLJKW PD[BSDVVHQJHUV DYHUDJHBZHLJKWZHLJKW UHBIXHO WRWDOBZHLJKW LPBGLVWDQFH IDFWRU (1'0(7+2' 0(7+2'HVWLPDWHBIXHO... WRWDOBZHLJKW PD[BFDUJRZHLJKW UHBIXHO WRWDOBZHLJKW LPBGLVWDQFH IDFWRU (1'0(7+2' SAP AG 2002 n Which coding is actually executed when estimate_fuel is called depends on the dynamic type of the reference variable r_vehicle, that is it depends on which object from which (sub)class r_vehicle refers to. n You can use polymorphism to write programs that are generic to a high degree and that do not even need to be changed if use cases are added. In the simple example above, this means that, should a further subclass be added, for example for motorbikes, the above coding would not need to be changed. A redefined method will be created in the server class lcl_motorbike. © SAP AG BC401 9-10 6WDWLFDQG'\QDPLF7\SHVRI5HIHUHQFHV l 7KHVWDWLFW\SHRIDUHIHUHQFHYDULDEOH ,VGHILQHGXVLQJ7<3(5()72 '$7$UBYHKLFOH 7<3(5()72OFOBYHKLFOH 5HPDLQVFRQVWDQWWKURXJKRXWWKHSURJUDPIORZ l 'HILQHVZKLFKDWWULEXWHVDQGPHWKRGVFDQEHDGGUHVVHG 7KHG\QDPLFW\SHRIDUHIHUHQFHYDULDEOH ,VGHILQHGE\DVVLJQPHQW &DQFKDQJHGXULQJWKHSURJUDPUXQ 'HILQHVZKLFKFRGHLVWREHH[HFXWHGIRU UHGHILQHGPHWKRGV Í Æ|ÎÅLÏÂLÐÉLÅ Ñ Ò ÓÔ L L i Õ ½iÖ|´iµ|¼¸¾´iº×¹ µ´iºi´»¼¾½´iº ¿ÀÁiÂÃÄÁ Å Æ Ç È|Å|É Ñ ÓÔ i | Õ ½iÖ|´iµ|¼¸¾´iº×¹ µ´iºi´»¼¾½´iº ¿ÀÁiÂÃÄÁ Å¾Æ Ç È|Å|É ¿ÀiÁÂà ÄÁLÅ·ÆÇLÈÅ|É ¿ÀiÁ|Âà ÄÁLÅ·ÆÇLÈÅ|É SAP AG 2002 n A reference variable always has two types, static and dynamic: é The static type of a reference variable is determined by variable definition using TYPE REF TO. It cannot and does not change. It specifies which attributes and methods can be addressed é The dynamic type of a reference variable is the type of the instance currently being referred to, it is therefore determined by assignment and can change during the program run. It defines what code is to be executed for redefined methods. n In the example, the static type of the r_vehicle variable is always REF TO lcl_vehicle, but its dynamic type after the cast is REF TO lcl_bus or REF TO lcl_truck. n In the Debugger, the reference me can be used to determine the dynamic type. © SAP AG BC401 9-11 &RPSDULVRQWR3URFHGXUDO3URJUDPPLQJ l l ,QREMHFWRULHQWHGSURJUDPPLQJ\RXGRQRWQHHGWRFKDQJHWKHFRGLQJLI \RXDGGXVHFDVHV ,QDSURFHGXUDOSURJUDP\RXZRXOGKDYHWRDGMXVW&$6(FRQVWUXFWLRQV IRUH[DPSOH 3URFHGXUDOUHDOLVDWLRQRIWKHH[DPSOHZLWKRXWSRO\PRUSKLVP '$7$YHKLFOHBOLVW7<3(7$%/(2)YHKLFOHBOLVWBW\SH YHKLFOH7<3(YHKLFOHBOLVWBW\SH YHKLFOHBOLVW /223$7YHKLFOHBOLVW,172YHKLFOH name FDWHJRU\ ... &$6(YHKLFOHFDWHJRU\ :+(1 758&. truck1 3(5)250HVWLPDWHBIXHOBWUXFN86,1* bus1 &+$1*,1*IXHO bus2 :+(1 %86 truck2 3(5)250HVWLPDWHBIXHOBEXV86,1* &+$1*,1*IXHO (1'&$6( $''IXHO72QHHGHGBIXHO (1'/223 truck3 SAP AG 2002 n Using polymorphism makes generic programming easier. Instead of implementing a CASE or IF statement, you can have one access or call, which improves readability and does not need to be changed if you extend the program by adding further subclasses. © SAP AG BC401 9-12 &DVWLQJ 1DUURZLQJFDVW 1DUURZLQJFDVW :LGHQLQJFDVW :LGHQLQJFDVW ,QKHULWDQFHDQGSRO\PRUSKLVP ,QKHULWDQFHDQGSRO\PRUSKLVP SAP AG 2002 © SAP AG BC401 9-13 8VHRI:LGHQLQJ&DVW i |L OFOBUHQWDO 7KHFOLHQW Public i L |i ØâÙÚ ¥J£ ÙWÛÜWÝ Þäãá Private g¡¢£W¤5¥U¤¢§W¨ JHWBPD[BFDUJR i 0(7+2'JHWBPD[BFDUJR '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH /223$7YHKLFOHBOLVW,172UBYHKLFOH 3UREOHPLVWKLVUHDOO\DWUXFN" 'HWHUPLQHWKHPD[FDUJR (1'/223 (1'0(7+2' i i i ØÔÙÚ ¥3£ ÙWÛÜgÝ Þàßá 7UXFNRURWKHU YHKLFOH" SAP AG 2002 n The client, the car rental company in the above example, wants to execute a function for specific vehicles form the list (vehicle_list). For example, the client wants to ascertain the truck with the largest cargo capacity. However, not all vehicles are in the trucks list, it also includes references to cars and busses. © SAP AG BC401 9-14 :LGHQLQJ&DVW([DPSOH Ñ Óâ i |L ð ñ|òôó õÔó ö-÷øJùúiû3ó OFOBUHQWDO Î ÅLÏÂLÐ|É Å·Æ ÉiÂiÀiÁ J i |i åæ¦çiè5é/ê ë èì ê+í åî ØâÙÚ ¥J£ ÙWÛÜWÝ Þäãá 3 i 0(7+2'JHWBPD[BFDUJR '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH UBWUXFN7<3(5()72OFOBWUXFN /223$7YHKLFOHBOLVW,172UBYHKLFOH 75< UBWUXFN" UBYHKLFOH SXWPD[FDUJRLQYDULDEOHUHBFDUJR &$7&+F[BV\BPRYHBFDVWBHUURU ï 3 i ØÔÙÚ ¥3£ ÙWÛÜgÝ Þàßá UHDFWRQWKDWFDVWHUURU (1'75< (1'/223 (1'0(7+2' SAP AG 2002 n The type of case described above is known as a widening cast (or "down cast") because it changes from a less detailed view to one with more detail. The target reference (r_truck in the above example) must correspond to the object reference (r_vehicle in the above example), that is the instance must have the details implied by the reference. n The widening cast logically represents the opposite of the narrowing cast. The widening cast cannot be checked statically, only at runtime. The &DVW2SHUDWRU ?=(or the equivalent MOVE ... ?TO … ) must be used to make this visible. n With this kind of cast, a check is carried out at runtime to ensure that the current content of the source variable corresponds to the type requirements of the target variables. In this example, it checks that the dynamic type of the source reference r_vehicle is compatible with the static type of the target reference r_truck. If it is, the assignment is carried out. Otherwise, an exception that can be handled is raised, and the original value of the target variable remains the same. This exception of the error class CX_SY_MOVE_CAST_ERROR can be caught using TRY-ENDTRY and the CATCH statement. (This will be discussed in more detail later.) n Another way of preventing the runtime error would be to use RTTI (Runtime Type Identification). This is a class library for ascertaining type attributes at runtime. © SAP AG BC401 9-15 &DVWLQJ 1DUURZLQJFDVW 1DUURZLQJFDVW :LGHQLQJFDVW :LGHQLQJFDVW ,QKHULWDQFHDQGSRO\PRUSKLVP ,QKHULWDQFHDQGSRO\PRUSKLVP SAP AG 2002 © SAP AG BC401 9-16 6HPDQWLFVDQG8VHZLWK,QKHULWDQFH 5XOHV l l l ,QKHULWHGFRPSRQHQWVPXVWEHKDYHLQVXEFODVVHV H[DFWO\DVWKH\GRLQVXSHUFODVVHVIRUDOOXVHUV :KHQ\RXUHGHILQHDPHWKRGLWVVHPDQWLFVPXVWUHPDLQ WKHVDPH\RXFDQQRWFKDQJHWKHVLJQDWXUH 8VLQJLQKHULWDQFH l $OORZV\RXWRHQKDQFHFODVVHVXVLQJ JHQHUDOL]DWLRQVSHFLDOL]DWLRQDQGKHQFHDFKLHYH EHWWHUVRIWZDUHVWUXFWXUH l 3URYLGHVSRVVLELOLW\RISRO\PRUSKLFEHKDYLRU JHQHULFSURJUDPPLQJ&$6(FRQVWUXFWLRQVQR ORQJHUQHHGHG ü 0XVWQRWEHXVHGVROHO\IRUFRGHLQKHULWDQFH SAP AG 2002 n A subclass instance can be used in any context in which a superclass instance also appears. Moreover: The user does not and is not intended to know whether they are dealing with a subclass or a superclass instance. The user works only with references to the superclass and must rely on the inherited components behaving in the subclass instances exactly as they do in the superclass instances, otherwise the program will not work. n On the other hand, this ensures useful restrictions on the implementation of the subclasses: Inherited components must keep their inherited semantics. You cannot use inherited attributes or events in any way other than intended in the superclass, and you cannot change method semantics by redefinition. n You must avoid "code inheritance": It is not correct for one class to inherit from another simply because SDUW of the functionality required is already implemented there. © SAP AG BC401 9-17 ,QFRUUHFW8VHRI,QKHULWDQFH 5XOHV l ,QKHULWDQFHLVRIWHQXVHGLQFRUUHFWO\ 7RVLPSO\UHXVHFRGH ü ,QVWHDGRIDGGLWLRQDODWWULEXWHVDJJUHJDWLRQUROH FRQFHSWV ü GH VL JQ " FDU FDUBUHG ü FDUBEOXH 7KHXVHRILQKHULWDQFHGRHVQRWDOZD\VFRUUHVSRQG WRH[SHFWDWLRQVLQWKHUHDOZRUOG FKDQJHBZLGWK ý 6XSHUFODVV ÿ þ FKDQJHBKHLJKW SAP AG 2002 GH VL JQ " 6XEFODVV +þ n Using inheritance instead of attributes, or a misunderstanding of inheritance as an is-one relationship often leads to the following kind of design: the superclass FDU has the subclasses UHGFDU, JUHHQFDU, and so on. These subclasses all have an identical structure and identical behavior. n Because an instance cannot change its class, in circumstances like the following, you should not use inheritance directly, but use a so-called role design pattern instead: The class HPSOR\HH has the subclasses IXOOWLPHHPSOR\HH and SDUWWLPHHPSOR\HH. What happens when a part-time employee becomes a full-time employee? A new full-time employee object would have to be instantiated and all the information copied from the part-time employee object. However, users who still have a reference to the part-time employee instance would then be working with a part-time employee object that logically does not exist anymore. n The use of inheritance does not always correspond to expectations in the real world: For example, if the class VTXDUH inherits from the class UHFWDQJOH, the latter will have two separate methods for changing length or width, although the sides of the square actually need to be changed by the same measurement. © SAP AG BC401 9-18 &DVWLQJ8QLW6XPPDU\ <RXDUHQRZDEOHWR l 8VHFDVWV l 'HYHORSJHQHULFSURJUDPVXVLQJSRO\PRUSKLVP ZLWKLQKHULWDQFH SAP AG 2002 © SAP AG BC401 9-19 &DVWLQJ([HUFLVHV 8QLW&DVWLQJ 7RSLF3RO\PRUSKLVP At the conclusion of these exercises, you will be able to: • Describe polymorphism and inheritance • Use generic programming for inheritance relationships and implement polymorphic method calls 0RGHOVROXWLRQ 6$3%&B&$66B0$,1B$ 6$3%&B,1+6B$include program 1-1 Extend your existing program =%&BB0$,1B$,53/$1( or start with the model solution from the last chapter’s exercises. 1-2 In your main program, define an internal table for buffering airplane objects. The type of the internal table should be 5()72OFOBDLUSODQH. 1-3 Try to insert the planes (passenger and cargo) into this internal table and execute the GLVSOD\BDWWULEXWHV method for every plane in a LOOP. Read the internal table in the LOOP using the auxiliary reference variable UBDLUSODQH (type 5()72OFOBDLUSODQH). 1-3-1 Was this successful? 1-3-2 Check the internal table and the execution of the GLVSOD\BDWWULEXWHV method in the Debugger 1-3-3 Which source code is executed when the GLVSOD\BDWWULEXWHVmethod is called, the original method from the superclass or the relevant redefined methods from the subclasses? What would happen if one of these methods had not been redefined in the subclass? 0RGHOVROXWLRQ 6$3%&B&$66B0$,1B% 6$3%&B&$66B%include program 7HPSODWH © SAP AG 6$3%&B&$67B% BC401 9-20 2-1 2-2 Copy the definition of the class OFOBFDUULHU from the template 6$3%&B&$67B% to your own include program =%&BB$,53/$1( (hence adding this class to your include program). Add the following public instance methods to the class OFOBFDUULHU: 2-2-1 The first method is DGGBDLUSODQH, which adds planes to the list of planes DLUSODQHBOLVW already defined in the class. The transfer parameter is a reference to the class OFOBDLUSODQH. Have a close look at the definition of the internal table DLUSODQHBOLVW. 2-2-2 The second method is GLVSOD\BDLUSODQHV, which displays the planes from the list DLUSODQHBOLVW. The GLVSOD\BDWWULEXWHV method from class OFOBDLUSODQH should be called at this point. 2-2-3 The third method is GLVSOD\BDWWULEXWHV, which displays the airline attributes. This includes the airline name and the list of planes (you can use LFRQBIOLJKW as an icon before the name). 2-3 Go back to your main program. 2-3-1 At the DATA statement, create a reference to the class OFOBFDUULHU. 2-3-2 Comment out all statements affecting the internal table (or delete them). 2-3-3 Create an airline and fill the transfer parameters with data of your own choice. 2-3-4 Add the planes already created in the last exercise (passenger and cargo planes) to the list of planes DLUSODQHBOLVW. To do this, call the method DGGBDLUSODQH of the class OFOBFDUULHU. Create more planes and add them to the airplane list. 2-3-5 Display the airline attributes by calling the GLVSOD\BDWWULEXWHV method of the class OFOBFDUULHU. 2-3-6 Question: Which code is executed when you execute GLVSOD\BDWWULEXWHV within GLVSOD\BDLUSODQHV. © SAP AG BC401 9-21 &DVWLQJ6ROXWLRQV 8QLW &DVWLQJ 7RSLF 3RO\PRUSKLVP *&---------------------------------------------------------------------* *& Report SAPBC401_CASS_MAIN_a * *& * *&---------------------------------------------------------------------* *& show casting operations ... * *&---------------------------------------------------------------------* REPORT sapbc401_cass_main_a. INCLUDE <icon>. INCLUDE sapbc401_inhs_a. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, SODQHBOLVW7<3(7$%/(2)5()72OFOBDLUSODQH START-OF-SELECTION. *############################## lcl_airplane=>display_n_o_airplanes( ). CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. $33(1'UBSDVVHQJHU72SODQHBOLVW CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ © SAP AG BC401 9-22 im_cargo = 533. $33(1'UBFDUJR72SODQHBOLVW /223$7SODQHBOLVW,172UBSODQH UBSODQH!GLVSOD\BDWWULEXWHV (1'/223 lcl_airplane=>display_n_o_airplanes( ). *&---------------------------------------------------------------------* *& Report SAPBC401_CASS_MAIN_b * *& * *&---------------------------------------------------------------------* *& carrier adds airplanes to its airplane_list --> polymorphism * *&---------------------------------------------------------------------* REPORT sapbc401_cass_main_b. INCLUDE <icon>. INCLUDE sapbc401_cass_b. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, UBFDUULHUW\SHUHIWROFOBFDUULHU START-OF-SELECTION. *############################## ***** Create Carrier ******************************************** FUHDWHREMHFWUBFDUULHUH[SRUWLQJLPBQDPH 6PLOH )O\7UDYHO ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ © SAP AG BC401 9-23 CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. ***** insert planes into itab if client *************************** UBFDUULHU!DGGBDLUSODQH UBSDVVHQJHU UBFDUULHU!DGGBDLUSODQH UBFDUJR ***** show all airplanes inside carrier *************************** UBFDUULHU!GLVSOD\BDWWULEXWHV *---------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *---------------------------------------------------------------------* * Class definitions of ... lcl_airplane, cargo- and passenger_plane * ... * ... *---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION *---------------------------------------------------------------------* &/$66OFOBFDUULHU'(),1,7,21 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*LPBQDPH7<3(VWULQJ JHWBQDPH5(7851,1*YDOXH H[BQDPH 7<3(VWULQJ DGGBDLUSODQH,03257,1* LPBSODQH7<3(5()72OFOBDLUSODQH GLVSOD\BDLUSODQHV GLVSOD\BDWWULEXWHV 35,9$7(6(&7,21 '$7$QDPH7<3(VWULQJ DLUSODQHBOLVWW\SH7$%/(2)5()72OFOBDLUSODQH (1'&/$66 © SAP AG BC401 9-24 *---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION *---------------------------------------------------------------------* &/$66OFOBFDUULHU,03/(0(17$7,21 0(7+2'DGGBDLUSODQH $33(1'LPBSODQH72DLUSODQHBOLVW (1'0(7+2' 0(7+2'GLVSOD\BDWWULEXWHV :5,7(LFRQBIOLJKW$6,&21QDPHXOLQHXOLQH GLVSOD\BDLUSODQHV (1'0(7+2' 0(7+2'GLVSOD\BDLUSODQHV GDWDUBSODQHW\SHUHIWROFOBDLUSODQH ORRSDWDLUSODQHBOLVWLQWRUBSODQH UBSODQH!GLVSOD\BDWWULEXWHV HQGORRS (1'0(7+2' 0(7+2'FRQVWUXFWRU QDPH LPBQDPH (1'0(7+2' 0(7+2'JHWBQDPH H[BQDPH QDPH (1'0(7+2' (1'&/$66 © SAP AG BC401 9-25 ,QWHUIDFHV &RQWHQWV l ,QWHUIDFHV l &RPSRXQGLQWHUIDFHV l 3RO\PRUSKLVP SAP AG 2002 © SAP AG BC401 10-1 ,QWHUIDFHV8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 'HILQHDQGLPSOHPHQWLQWHUIDFHV l 'HYHORSJHQHULFSURJUDPVXVLQJSRO\PRUSKLVP ZLWKLQWHUIDFHV SAP AG 2002 © SAP AG BC401 10-2 ,QWHUIDFHV,QWHJUDWLRQLQ&RXUVH&RQWHQW D @ < @ BE?F = 6 @ 6 8 7 G8 D @ < @IH CKJ =L < D = <@ 7A rtsIu vwx?yUz vU{ q l b h\] k n ]2o a [p\ h l ] ^ a \] [\ a ] h a?j Z [ ck [ lm m k Z,[\ ]^ \ _ ` a b0c2d2ef g a ^?h i e # # ! " 56 7 89;: 8< =?> 8 @A B @ C A= 6 $ %& & ' ()*,+- ) + %.0/ % (21 * % / / ' ( )3 %4 % MONP Q RSUTWV S Q ?V X S?Y SAP AG 2002 © SAP AG BC401 10-3 ,QWHUIDFHV ,QWHUIDFHV3ULQFLSOHV ,QWHUIDFHV3ULQFLSOHV :RUNLQJZLWKLQWHUIDFHV :RUNLQJZLWKLQWHUIDFHV 3UHYLHZ&RPSRXQGLQWHUIDFHV 3UHYLHZ&RPSRXQGLQWHUIDFHV SAP AG 2002 © SAP AG BC401 10-4 ,QWHUIDFHV8VH 6HUYLFH 6HUYLFH 6HUYLFH " ,QWHUIDFHV |~} OFOBFDUULHU OFOBUHQWDO OFOBKRWHO OFOBYHKLFOHV OFOBDLUSODQH SAP AG 2002 n In ABAP Objects, interfaces are implemented in addition to and independently of classes. Interfaces only describe the external point of contact of a class (protocols), they do not contain any implementation. n Interfaces are usually defined by a user. The user describes in the interface which services (technical and semantic) it needs in order to carry out a task. The user never actually knows the providers of these services, but communicates with them through the interface. In this way the user is protected from actual implementations and can work in the same way with different classes/objects, as long as they provide the services required. This is known as SRO\PRUSKLVPwith interfaces. © SAP AG BC401 10-5 ,QWHUIDFHV6HUYLFHV KKIU GLVSOD\BSDUWQHU FKHFNBDYDLODELOLW\ ,QWHUIDFH |~} OFOBFDUULHU OFOBUHQWDO OFOBKRWHO OFOBYHKLFOHV OFOBDLUSODQH SAP AG 2002 n In the above example, a client wants to use the same services of different server classes (lcl_carrier, lcl_hotel, and lcl_rental) in the same way. There are different implementations of the services in the server classes (polymorphism). n The following are examples of shared services of the server classes in the above case: display_partner, check_availability, booking, or cancel_booking. © SAP AG BC401 10-6 ,QWHUIDFH80/([DPSOH OFOBWUDYHOBDJHQF\ XVHV &OLHQW ,WLVSRVVLEOHWR ,PSOHPHQWDWLRQ LPSOHPHQWVHYHUDO PHKUHUHU,QWHUIDFHV LQWHUIDFHV P|JOLFK ,QWHUIDFH!! ,QWHUIDFH!! OLIBSDUWQHUV OLIBOLFHQVH LPSOHPHQWV OFOBFDUULHU OFOBUHQWDO OFOBKRWHO OFOBYHKLFOHV OFOBDLUSODQH SAP AG 2002 n In UML, interfaces can represented in the same way as classes. However, they always have the stereotype «interface» above their name and can therefore be distinguished from classes. n The use of an interface is represented by a dotted line with a two-sided arrow from the user to the interface, the stereotype «uses» is optional. The fact that a class implements an interface is represented by a dotted line with a three-sided arrow from the class to the interface. The similarity to the representation of inheritance is intentional, because the interface can be seen as a generalization of the class implemented or the class can be seen as a specialization of the interface. n In ABAP Objects, the same components can be defined in interfaces and in classes. This allows you to shift part of the public point of contact of a class into an interface, even though the class is already in use; users will not notice the difference as long as you use alias names (see appendix) for the components that are now in the interface. n A class can implement any number of interfaces and an interface can be implemented by any number of classes. By implementing several interfaces, a class can simulate multiple inheritance. In the example, lcl_rental implements the interfaces lif_partners and lif_license. © SAP AG BC401 10-7 'HILQLQJDQG,PSOHPHQWLQJDQ,QWHUIDFH l 'HFODULQJWKH LQWHUIDFH l 7KHVHUYHUFODVVHV PDNHWKHLQWHUIDFH SXEOLF l ,QWHUIDFHVDUH LPSOHPHQWHGLQFODVVHV l ,QWHUIDFHVGRQRWKDYH YLVLELOLW\VHFWLRQV ,17(5)$&(OLIBSDUWQHUV 0(7+2'6GLVSOD\BSDUWQHU (1',17(5)$&( &/$66OFOBUHQWDO'(),1,7,21 38%/,&6(&7,21 ,17(5)$&(6OLIBSDUWQHUV (1'&/$66 &/$66OFOBUHQWDO,03/(0(17$7,21 0(7+2'OLIBSDUWQHUVaGLVSOD\BSDUWQHU MXVWFDOOH[LVWLQJPHWKRGWKDWILWV GLVSOD\BDWWULEXWHV ... (1'0(7+2' ,QWHUIDFH UHVROXWLRQ (1'&/$66 RSHUDWRU SAP AG 2002 n In ABAP Objects, the same components (attributes, methods, constants, types, alias names) can be defined in an interface in largely the same way as in classes. However, interfaces do not have component visibility levels. n Interfaces are implemented in classes. • The interface name is listed in the definition part of the class. Interfaces can only be implemented publicly and are therefore always in the PUBLIC SECTION. If you do not do this, you risk multiple implementations if a superclass and a subclass both implement the same interface privately. • The operations defined in the interface are implemented as methods of a class. A check is carried out to ensure that all the methods defined in the interfaces are actually present in the implementation part of the class (for global interfaces, a missing or superfluous implementation of an interface method results in a warning). • The attributes, events, constants, and types defined in the interface are automatically available to the class carrying out the implementation. n Interface components are addressed in the class carrying out the implementation by prefixing the interface name, followed by a tilde (the ,QWHUIDFH5HVROXWLRQ2SHUDWRU): <interfacename>~<componentname>. n Changes to an interface usually invalidate all the classes implementing it. © SAP AG BC401 10-8 ,QWHUIDFHV)HDWXUHV l 6HSDUDWLRQRIH[WHUQDOSRLQWRIFRQWDFW LQWHUIDFH DQGLPSOHPHQWDWLRQ FODVV 7KHFOLHQWGHILQHVWKHSURWRFROWKHVHUYHULPSOHPHQWVLW ¡ %ODFN%R[SULQFLSOH&OLHQWRQO\NQRZVWKHLQWHUIDFHQRW WKHLPSOHPHQWDWLRQ ¡ /RRVHUOLQNDJHEHWZHHQFOLHQWDQGVHUYHU ¡ l 3RO\PRUSKLVP *HQHULFKDQGOLQJRIREMHFWVRIGLIIHUHQWFODVVHV ¡ l W0 ,´ µ¶· ¸ ¹»º¶ ¸¼ ½p¾ W¼ 0³ W2²± $EVWUDFWLRQ ¡ l OU ,QWHUIDFHDVDJHQHUDOL]DWLRQRI WKHLPSOHPHQWLQJFODVV ¬p­® ¦W¨ ¯K° ¢¤£¥§¦¨ © 6LPXODWLRQRIPXOWLSOHLQKHULWDQFH ¢W£Wª¤© ¢£OªO« SAP AG 2002 n Interfaces are the means of choice for describing external points of contact or protocols, without linking them to a type of implementation. An extra layer is introduced between the client and the server to protect the client explicitly from the server, thereby making the client independent. n Interfaces enable you to work uniformly with different classes (providers/servers). In particular, they always ensure polymorphic behavior as they do not have their own implementation, but instead allow the providers to carry it out. n The definition of an interface is always an abstraction: The user wants to handle various providers in the same way and must therefore abstract concrete implementations to a description of the services required to fulfill the task. n You can also use interfaces to achieve multiple inheritance by defining the functionality to be inherited by a second class as an interface that the inheriting class then has to implement. © SAP AG BC401 10-9 ,QWHUIDFHV ,QWHUIDFHV3ULQFLSOHV ,QWHUIDFHV3ULQFLSOHV :RUNLQJZLWKLQWHUIDFHV :RUNLQJZLWKLQWHUIDFHV 3UHYLHZ&RPSRXQGLQWHUIDFHV 3UHYLHZ&RPSRXQGLQWHUIDFHV SAP AG 2002 © SAP AG BC401 10-10 :RUNLQJZLWK,QWHUIDFH&RPSRQHQWV &/$66OFOBUHQWDO,03/(0(17$7,21 0(7+2'OLIBSDUWQHUVaGLVSOD\BSDUWQHU VSHFLDOFRGLQJWRGLVSOD\SDUWQHUVRU MXVWFDOOLQJH[LVWLQJPHWKRGWKDWILWV GLVSOD\BDWWULEXWHV (1'0(7+2' (1'&/$66 OLIBSDUWQHUV GLVSOD\BSDUWQHU FKHFNBDYDLODELOLW\ LPSOHPHQWV '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH ... &5($7(2%-(&7UBYHKLFOH V\QWDFWLFDOO\SRVVLEOHEXWQRWXVHIXO UBYHKLFOH!OLIBSDUWQHUVaGLVSOD\BSDUWQHU OFOBUHQWDO QDPH YHKLFOHBOLVW DGGBYHKLFOH GLVSOD\BDWWULEXWHV ,QWHUIDFHUHVROXWLRQRSHUDWRU SAP AG 2002 n You can access interface components using an object reference, whose class implements the interface. Syntactically this is done with the interface resolution operator, just as with the method definitions in the implementation part of the class. n This allows you to differentiate between components defined in the interface and components of the same name that are defined in the class itself. The reason for this is the shared namespace. n To simplify accessing interface methods you can work with DOLDV names. é Alias names can only appear in the in the declaration part of a class or in the interface definition. é Example for an alias in the interface: ALIASES a1 FOR lif_interface~method1 An alias defined in this way can be directly addressed using r_ref->a1. © SAP AG BC401 10-11 ,QWHUIDFH5HIHUHQFHV1DUURZLQJ&DVW '$7$UBUHQWDO7<3(5()72OFOBUHQWDO UBOLI7<3(5()72OLIBSDUWQHUV OFOBUHQWDO &5($7(2%-(&7UBUHQWDO Public ¿ÁÀ¿ ;ÃÂ; Private ¿ÁÀ KKÄ ,QWHUIDFH FRPSRQHQWV 1DUURZLQJ&DVW UBOLI UBUHQWDO GLVSOD\BSDUWQHU FKHFNBDYDLODELOLW\ ¿ÁÀ tKÄ SAP AG 2002 n Interfaces are addressed using interface references. Interface references always refer to instances in the classes carrying out the implementation. Interface references always have both static and dynamic types. n The assignment of an object reference to an interface reference is known as a narrowing cast since, as with inheritance, only a part of the object interface is visible once you have assigned the reference. n With an interface reference, you can no longer address all components in the class carrying out the implementation, but only the components defined in the interface. These components are now addressed using the interface reference exclusively with their own short name. n When an object reference is assigned to an interface reference, you must be able to convert the dynamic type of the interface reference to the static type of the object reference - that is, the class that was used to define the object reference must have implemented the interface of the interfacereference. © SAP AG BC401 10-12 8VLQJWKH,QWHUIDFH OFOBWUDYHOBDJHQF\ Public Å§Æ Ç Æ È É Ê Ë ÌÍÆ Private ÎÏÐÑÒWÓ¤ÐÔIÕÖ×WÑ DGGBSDUWQHU ÅOÆ Ç Æ È Ø ÌÍÙtË ÚÍÆ Å§Æ Ç Æ È»ÇtÚ Ø Ø Û ÌÍØ ... 0(7+2'6DGGBSDUWQHU,03257,1*LPBSDUWQHU7<3(5()72OLIBSDUWQHUV ... SAP AG 2002 n The travel agent is a user (client) of the created interface. The travel agency keeps references to its business partners in an internal table. Th type of this internal table is REF TO lif_partners, that is the reference to the interface lif_partners. n When it is called, the client’s public method add_partner is transferred the business partner references. In the method, the references are inserted into the table partner_list. Therefore, the interface parameter of the add_partner method has the type REF TO lif_partners. n The aim here is polymorphism: It needs to be possible to generically access the services of the interface later. © SAP AG BC401 10-13 3RO\PRUSKLVPDQG,QWHUIDFHV 0(7+2'GLVSOD\BDJHQF\BSDUWQHUV '$7$UBSDUWQHU7<3(5()72OLIBSDUWQHUV /223$7SDUWQHUBOLVW,172UBSDUWQHU UBSDUWQHU!GLVSOD\BSDUWQHU (1'/223 (1'0(7+2' Ü à Þ²Æ Ç Æ È ÉÁÊtË Ì Æ ÎÏWÐÑÒWÓWÐ2ÔIÕÖ×OÑ Ü Ý ÞÆ ÇKÆ È Ø ÌÍÙßË ÚÍÆ Ü á ÞÆ Ç Æ È»ÇtÚ Ø Ø Û ÌÍØ 0(7+2'aGLVSOD\BSDUWQHU GLVSOD\BKRWHOBDWWULEXWHV ... (1'0(7+2' 0(7+2'aGLVSOD\BSDUWQHU GLVSOD\BUHQWDOBGDWD ... (1'0(7+2' 0(7+2'aGLVSOD\BSDUWQHU GLVSOD\BDWWULEXWHV ... (1'0(7+2' SAP AG 2002 n Polymorphism can also be used for interfaces: you can use interface references to call methods that can have a GLIIHUHQWLPSOHPHQWDWLRQ depending on the object behind the reference. n The dynamic type, not the static type of the reference variable is used to search for the implementation of a method. In the above example, r_partner->display_partner( ) therefore uses the class of the instance that r_partner actually refers to to search for the implementation of display. The static type for r_partner, which is always REF TO lif_partners, is not used. © SAP AG BC401 10-14 ,QWHUIDFH5HIHUHQFHV:LGHQLQJ&DVW Å§Æ Ç Æ È»ÉÍÊtË ÌÍÆ öø÷ ù²÷ ú²û üÍýWþ²ÿ0÷ úIý0ÿ0ù OFOBUHQWDO ì?í îÍïtðÍñÍîpò ó ô õ ï âãã ä»åæçè éêë 0(7+2'ERRNBIOLJKW '$7$UBFDUULHU7<3(5()72OFOBFDUULHU UBSDUWQHU7<3(5()72OFOBSDUWQHU /223$7SDUWQHUBOLVW,172UBSDUWQHU 75< UBFDUULHU" UBSDUWQHU FDOOPHWKRGRIOFOBFDUULHUWRERRNIOLJKW &$7&+F[BV\BPRYHBFDVWBHUURU UHDFWRQWKDWFDVWHUURU (1'75< (1'/223 (1'0(7+2' Å§Æ Ç Æ È Ø Ì ÙßË ÚÍÆ Å§Æ Ç Æ È»ÇtÚ Ø Ø Û ÌÍØ SAP AG 2002 n The widening cast is, as with inheritance, the opposite of the narrowing cast: Here it is used to retrieve a class reference from an interface reference. Obviously it cannot be statically checked, since an interface can be implemented by more than one class. n An object reference cannot be assigned to an interface reference if it has itself not implemented the corresponding interface. It cannot be assigned even if a subclass has implemented the interface and the interface reference points to an object in this class. n Assignments between interface references whose interfaces are not related to each other cannot be checked statically and must therefore be formulated using the cast operator ?=. n For this type of assignment, a check must be carried out at runtime to see whether the class of the instance that the source reference points to also supports the interface that the target reference refers to. If this is the case, the cast is carried out, otherwise the exception that can be handled of the class CX_SY_MOVE_CAST_ERROR is raised. © SAP AG BC401 10-15 ,QWHUIDFHV ,QWHUIDFHV3ULQFLSOHV ,QWHUIDFHV3ULQFLSOHV :RUNLQJZLWKLQWHUIDFHV :RUNLQJZLWKLQWHUIDFHV 3UHYLHZ&RPSRXQGLQWHUIDFHV 3UHYLHZ&RPSRXQGLQWHUIDFHV SAP AG 2002 © SAP AG BC401 10-16 &RPSRXQG,QWHUIDFHV ,QWHUIDFH OLIBSDUWQHUV OFOBFDUULHU OFOBKRWHO 6ROXWLRQ &RPSRXQG LQWHUIDFHV ,QWHUIDFH OLIBURRPBERRNLQJ " OFOBUHQWDO 3UREOHP ([WHQGLQJ LQWHUIDFHV OLIBSDUWQHUV ,QWHUIDFH OFOBKRWHO OFOBFDUULHU OFOBUHQWDO SAP AG 2002 n ABAP Objects contains a composition model for interfaces. A compound interface contains other interfaces as components (component interfaces) and summarizes the extension of these component interfaces. An elementary interface does not itself contain other interfaces. n One interface can be used as a component interface in several compound interfaces. n UML only deals with the specialization and generalization of interfaces. This relationship is represented by a dotted line with a three-sided arrow from the specialized to the generalized interface. n Compound interfaces in ABAP Objects can always be seen as specializations of their component interfaces and represented as such in UML. © SAP AG BC401 10-17 &RPSRXQG,QWHUIDFHV([DPSOH ,17(5)$&(OLIBSDUWQHUV 0(7+2'6GLVSOD\BSDUWQHU (1',17(5)$&( ,17(5)$&(OLIBURRPBERRNLQJ ,17(5)$&(6OLIBSDUWQHUV 0(7+2'6ERRNBURRP (1',17(5)$&( &/$66OFOBKRWHO'(),1,7,21 38%/,&6(&7,21 ,17(5)$&(6OLIBURRPBERRNLQJ (1'&/$66 &/$66OFOBKRWHO,03/(0(17$7,21 0(7+2'OLIBSDUWQHUVaGLVSOD\BSDUWQHU (1'0(7+2' 0(7+2'OLIBURRPBERRNLQJaERRNBURRP (1'0(7+2' (1'&/$66 '$7$LBSDUWQHU7<3(5()72OLIBSDUWQHUV LBURRPBERRN7<3(5()72OLIBURRPBERRNLQJ ... LBSDUWQHU LBURRPBERRN³1DUURZLQJ&DVW LBURRPBERRN!OLIBSDUWQHUVaGLVSOD\BSDUWQHU LBSDUWQHU!GLVSOD\BSDUWQHU DOVRSRVVLEOH LBURRPBERRN" LBSDUWQHU³:LGHQLQJ&DVW SAP AG 2002 n In a compound interface, the components of the component interface keep their original names, that is <component-interfacename>~<componentname>; no more prefixes are added. In other words, all components in a compound interface are on the same level, and components inherited from component interfaces are marked with the usual interface prefix. n This equality principle for compound interfaces also affects how they are implemented. The procedure is as follows: First, implement the elementary interfaces, then the additional methods from the compound interfaces. For multiple compound interfaces, the process is simply repeated. In the class carrying out the implementation, all components of all interfaces implemented are again on the same level. n This means that interface components only ever exist once and are known by their original names <interfacename>~<componentname>. This is true both for compound interfaces and for the classes that implement them. © SAP AG BC401 10-18 ,QWHUIDFHV8QLW6XPPDU\ <RXDUHQRZDEOHWR l 'HILQHDQGLPSOHPHQWLQWHUIDFHV l 'HYHORSJHQHULFSURJUDPVXVLQJSRO\PRUSKLVP ZLWKLQWHUIDFHV SAP AG 2002 © SAP AG BC401 10-19 ,QWHUIDFHV([HUFLVHV 8QLW,QWHUIDFHV 7RSLF'HILQLQJ,QWHUIDFHV At the conclusion of these exercises, you will be able to: • Define and implement interfaces 0RGHOVROXWLRQ 6$3%&B,176B0$,1B$ 6$3%&B9(+'B)include program 6$3%&B,176B$include program 1 The classes OFOBUHQWDOOFOBYHKLFOH, and their subclasses are to be added to the existing UML diagram. The classes OFOBUHQWDO OFOBFDUULHU, and later OFOBKRWHO will all store separate services and provide a possible client (to be defined later) using an interface OLIBSDUWQHUV. 1-1 1-2 1-3 © SAP AG Add the interface OLIBSDUWQHUV to your UML diagram. GLVSOD\BSDUWQHU is to be the only interface method. What are the roles of the classes OFOBUHQWDO OFOBFDUULHU, and OFOBKRWHO?Depict this in the UML diagram by adding text and arrows. Fill in the UML diagram on the next page. Copy the include program 6$3%&B9(+'B)to your own include program =%&BB9(+,&/(. As well as the classes OFOBUHQWDOOFOBYHKLFOHOFOBWUXFN OFOBEXV, the program also contains the interface OLIBSDUWQHUV. Incorporate this include program into your main program. Add the types W\BIXHO and W\BFDUJR (both TYPE P DECIMALS 2) to the main program. Pay attention to the position of the interface definition; you may have to change the order of the include programs or move the interface into the other include program. Familiarize yourself with the interface definition. BC401 10-20 1-4 1-5 Now implement theinterface of your class OFOBFDUULHU. In the main program, create some instances for OFOBUHQWDO, OFOBYHKLFOH, and so on by copying the relevant code from the template 6$3%&B9(+7B0$,1B$. Call the method GLVSOD\BDWWULEXWHV of the class OFOBUHQWDO. Start your program. You should see an airline with your planes and a car rental company with various vehicles. (You will use the interface in the next exercise.) UML-Template for Exercise 1-1 © SAP AG BC401 10-21 ([HUFLVHV 8QLW,QWHUIDFHV 7RSLF8VLQJ,QWHUIDFHV At the conclusion of these exercises, you will be able to: • Define and implement interfaces • Use polymorphism with interfaces 0RGHOVROXWLRQ 6$3%&B,176B0$,1B% 6$3%&B9(+'B*include program 6$3%&B,176B$include program 2 Now the class OFOBWUDYHOBDJHQF\ (travel agency) is to be added to the existing UML diagram. It will use the interface to access the classes OFOBUHQWDO OFOBFDUULHUOFOBKRWHO(not yet implemented). 2-1 2-2 Add the class OFOBWUDYHOBDJHQF\ to your UML diagram. What is the role of this class?Depict this in the UML diagram by adding text and arrows. Fill in the UML diagram on the next page. Copy the definition of the class OFOBWUDYHOBDJHQF\from the template 6$3%&B9(+7B% to your own include program. Then complete this new class. 2-2-1 The travel agency uses the public method DGGBSDUWQHU to add business partners (that is car rental companies and airlines) to the internal table SDUWQHUBOLVW. 2-2-2 What are the types of the internal table and the interface parameter of DGGBSDUWQHU? 2-2-3 The travel agency will use the method GLVSOD\BDJHQF\BSDUWQHUV to display the data of its business partners. © SAP AG BC401 10-22 2-3 Go back to your main program. 2-4 Create an instance of the class OFOBWUDYHOBDJHQF\. 2-4-1 Use the DGGBSDUWQHU method to add the travel agency’s business partners to the internal table. 2-4-2 Use the GLVSOD\BDJHQF\BSDUWQHUV method to display the travel agency’s business partners. 2-4-3 At which point does polymorphism take place? Follow this in the Debugger. UML-Template for Exercise 2-1 © SAP AG BC401 10-23 ,QWHUIDFHV6ROXWLRQV 8QLW ,QWHUIDFHV 7RSLF 'HILQLQJ,QWHUIDFHV *&---------------------------------------------------------------------* *& Report SAPBC401_INTS_MAIN_A * *& * *&---------------------------------------------------------------------* *& include interface lif_partners and include file with lcl_vehicle.. * *&---------------------------------------------------------------------* REPORT sapbc401_ints_main_a. types ty_fuel type p decimals 2. types ty_cargo type p decimals 2. INCLUDE <icon>. INCLUDE sapbc401_vehd_f. include sapbc401_ints_a. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, UBFDUULHUW\SHUHIWROFOBFDUULHU UBDJHQF\W\SHUHIWROFOBWUDYHOBDJHQF\ UBUHQWDOW\SHUHIWROFOBUHQWDO UBWUXFNW\SHUHIWROFOBWUXFN UBEXVW\SHUHIWROFOBEXV START-OF-SELECTION. *############################## ***** Create Carrier ******************************************** FUHDWHREMHFWUBFDUULHUH[SRUWLQJLPBQDPH 6PLOH )O\7UDYHO ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING © SAP AG BC401 10-24 im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. ***** insert planes into itab if client *************************** UBFDUULHU!DGGBDLUSODQH UBSDVVHQJHU UBFDUULHU!DGGBDLUSODQH UBFDUJR ***** show all airplanes inside carrier *************************** UBFDUULHU!GLVSOD\BDWWULEXWHV ******* create RENTAL ***************************************** &5($7(2%-(&7UBUHQWDO(;3257,1*LPBQDPH +$33<&$55(17$/ ******* create truck ***************************************** &5($7(2%-(&7UBWUXFN(;3257,1*LPBPDNH 0$1 LPBFDUJR UBUHQWDO!DGGBYHKLFOH UBWUXFN ******* create truck ***************************************** &5($7(2%-(&7UBEXV(;3257,1*LPBPDNH 0HUFHGHV LPBSDVVHQJHUV UBUHQWDO!DGGBYHKLFOH UBEXV ******* create truck ***************************************** &5($7(2%-(&7UBWUXFN(;3257,1*LPBPDNH 92/92 LPBFDUJR UBUHQWDO!DGGBYHKLFOH UBWUXFN © SAP AG BC401 10-25 *&---------------------------------------------------------------------* *& Include SAPBC401_INTS_a * *&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* ... *---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION *---------------------------------------------------------------------* *---------------------------------------------------------------------* &/$66OFOBFDUULHU'(),1,7,21 38%/,&6(&7,21 ,17(5)$&(6OLIBSDUWQHUV 0(7+2'6FRQVWUXFWRU,03257,1*LPBQDPH7<3(VWULQJ JHWBQDPH5(7851,1*YDOXH H[BQDPH 7<3(VWULQJ DGGBDLUSODQH,03257,1* LPBSODQH7<3(5()72OFOBDLUSODQH GLVSOD\BDLUSODQHV GLVSOD\BDWWULEXWHV 35,9$7(6(&7,21 '$7$QDPH7<3(VWULQJ DLUSODQHBOLVW7<3(7$%/(2)5()72OFOBDLUSODQH (1'&/$66OFOBFDUULHU'(),1,7,21 *---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION *---------------------------------------------------------------------* &/$66OFOBFDUULHU,03/(0(17$7,21 0(7+2'OLIBSDUWQHUVaGLVSOD\BSDUWQHU GLVSOD\BDLUSODQHV (1'0(7+2'OLIBSDUWQHUVaGLVSOD\BSDUWQHU 0(7+2'DGGBDLUSODQH $33(1'LPBSODQH72DLUSODQHBOLVW (1'0(7+2'DGGBDLUSODQH 0(7+2'GLVSOD\BDWWULEXWHV :5,7(LFRQBIOLJKW$6,&21QDPH8/,1(8/,1( © SAP AG BC401 10-26 GLVSOD\BDLUSODQHV (1'0(7+2'GLVSOD\BDWWULEXWHV 0(7+2'GLVSOD\BDLUSODQHV '$7$UBSODQH7<3(5()72OFOBDLUSODQH /223$7DLUSODQHBOLVW,172UBSODQH UBSODQH!GLVSOD\BDWWULEXWHV (1'/223 (1'0(7+2'GLVSOD\BDLUSODQHV 0(7+2'FRQVWUXFWRU QDPH LPBQDPH (1'0(7+2'FRQVWUXFWRU 0(7+2'JHWBQDPH H[BQDPH QDPH (1'0(7+2'JHWBQDPH (1'&/$66OFOBFDUULHU,03/(0(17$7,21 © SAP AG BC401 10-27 6ROXWLRQV 8QLW ,QWHUIDFHV 7RSLF 8VLQJ,QWHUIDFHV *&---------------------------------------------------------------------* *& Report SAPBC401_INTS_MAIN_B * *& * *&---------------------------------------------------------------------* *& include interface lif_partners and include file with lcl_vehicle.. * *& the client (travel_agency) uses the interface... * *&---------------------------------------------------------------------* REPORT sapbc401_ints_main_b. types ty_fuel type p decimals 2. types ty_cargo type p decimals 2. INCLUDE <icon>. INCLUDE sapbc401_vehd_g. include sapbc401_ints_a. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, r_carrier type ref to lcl_carrier, UBDJHQF\W\SHUHIWROFOBWUDYHOBDJHQF\ UBUHQWDOW\SHUHIWROFOBUHQWDO UBWUXFNW\SHUHIWROFOBWUXFN UBEXVW\SHUHIWROFOBEXV START-OF-SELECTION. *############################## ***** Create TRAVEL_AGENCY ************************************** &5($7(2%-(&7UBDJHQF\(;3257,1*LPBQDPH )O\ 6PLOH7UDYHO © SAP AG BC401 10-28 ***** Create CARRIER ******************************************** create object r_carrier exporting im_name = ’Smile&Fly-Travel’. ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. ***** insert planes into itab if client *************************** r_carrier->add_airplane( r_passenger ). r_carrier->add_airplane( r_cargo ). ***** insert business-parnter of agency into partner_list*********** UBDJHQF\!DGGBSDUWQHU UBFDUULHU ******* create RENTAL ***************************************** &5($7(2%-(&7UBUHQWDO(;3257,1*LPBQDPH +$33<&$55(17$/ ******* create truck ***************************************** &5($7(2%-(&7UBWUXFN(;3257,1*LPBPDNH 0$1 LPBFDUJR UBUHQWDO!DGGBYHKLFOH UBWUXFN ******* create truck ***************************************** &5($7(2%-(&7UBEXV(;3257,1*LPBPDNH 0HUFHGHV LPBSDVVHQJHUV UBUHQWDO!DGGBYHKLFOH UBEXV ******* create truck ***************************************** &5($7(2%-(&7UBWUXFN(;3257,1*LPBPDNH 92/92 LPBFDUJR UBUHQWDO!DGGBYHKLFOH UBWUXFN ***** insert business-partner of agency into partner_list*********** UBDJHQF\!DGGBSDUWQHU UBUHQWDO ******* show attributes of all partners of travel_agency ****** UBDJHQF\!GLVSOD\BDJHQF\BSDUWQHUV © SAP AG BC401 10-29 *&---------------------------------------------------------------------* *& Include SAPBC401_VEHD_g * *&---------------------------------------------------------------------* *---------------------------------------------------------------------* * define client lcl_travel_agency * it will use the interface lif_partners *---------------------------------------------------------------------* ,17(5)$&(OLIBSDUWQHUV 0(7+2'6GLVSOD\BSDUWQHU (1',17(5)$&(OLIBSDUWQHUV *---------------------------------------------------------------------* * CLASS lcl_vehicle DEFINITION *---------------------------------------------------------------------* CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. "------------------METHODS: get_average_fuel IMPORTING im_distance TYPE s_distance im_fuel TYPE ty_fuel RETURNING value(re_avgfuel) TYPE ty_fuel. METHODS constructor IMPORTING im_make TYPE string. METHODS display_attributes. METHODS set_make IMPORTING im_make TYPE string. METHODS get_make EXPORTING ex_make TYPE string. CLASS-METHODS get_count EXPORTING re_count TYPE i. PRIVATE SECTION. "------------------DATA: make TYPE string. METHODS init_make. CLASS-DATA: n_o_vehicles TYPE i. ENDCLASS. © SAP AG "lcl_vehicle DEFINITION BC401 10-30 *---------------------------------------------------------------------* * CLASS lcl_vehicle IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION. METHOD get_average_fuel. re_avgfuel = im_distance / im_fuel. ENDMETHOD. "get_average_fuel METHOD constructor. make = im_make. ADD 1 TO n_o_vehicles. ENDMETHOD. "constructor METHOD set_make. IF im_make IS INITIAL. init_make( ). " me->init_make( ). also possible ELSE. make = im_make. ENDIF. ENDMETHOD. "set_make METHOD init_make. make = ’default make’. ENDMETHOD. "init_make METHOD get_make. ex_make = make. ENDMETHOD. "get_make METHOD display_attributes. WRITE: make. ENDMETHOD. "display_attributes METHOD get_count. re_count = n_o_vehicles. ENDMETHOD. ENDCLASS. © SAP AG "get_count "lcl_vehicle IMPLEMENTATION BC401 10-31 *---------------------------------------------------------------------* * CLASS lcl_truck DEFINITION *---------------------------------------------------------------------* CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. "------------------METHODS: constructor IMPORTING im_make TYPE string im_cargo TYPE ty_cargo. METHODS display_attributes REDEFINITION. METHODS get_cargo RETURNING value(re_cargo) TYPE ty_cargo. PRIVATE SECTION. "------------------DATA: max_cargo TYPE ty_cargo. ENDCLASS. "lcl_vehicle DEFINITION *---------------------------------------------------------------------* * CLASS lcl_truck IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_truck IMPLEMENTATION. METHOD constructor. super->constructor( im_make ). max_cargo = im_cargo. ENDMETHOD. "constructor METHOD display_attributes. WRITE: / icon_ws_truck AS ICON. super->display_attributes( ). WRITE: 20 ’ Cargo = ’, max_cargo. ULINE. ENDMETHOD. "display_attributes METHOD get_cargo. re_cargo = max_cargo. ENDMETHOD. ENDCLASS. © SAP AG "get_cargo "lcl_vehicle DEFINITION BC401 10-32 *---------------------------------------------------------------------* * CLASS lcl_bus DEFINITION *---------------------------------------------------------------------* CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. "------------------METHODS: constructor IMPORTING im_make TYPE string im_passengers TYPE i. METHODS display_attributes REDEFINITION. PRIVATE SECTION. "------------------DATA: max_passengers TYPE i. ENDCLASS. "lcl_vehicle DEFINITION *---------------------------------------------------------------------* * CLASS lcl_bus IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_bus IMPLEMENTATION. METHOD constructor. super->constructor( im_make ). max_passengers = im_passengers. ENDMETHOD. "constructor METHOD display_attributes. WRITE: / icon_transportation_mode AS ICON. super->display_attributes( ). WRITE: 20 ’ Passengers = ’, max_passengers. ULINE. ENDMETHOD. ENDCLASS. © SAP AG "display_attributes "lcl_vehicle DEFINITION BC401 10-33 *---------------------------------------------------------------------* * CLASS lcl_rental DEFINITION *---------------------------------------------------------------------* &/$66OFOBUHQWDO'(),1,7,21 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*LPBQDPH7<3(VWULQJ 0(7+2'6DGGBYHKLFOH,03257,1*LPBYHKLFOH 7<3(5()72OFOBYHKLFOH 0(7+2'6GLVSOD\BDWWULEXWHV ,17(5)$&(6OLIBSDUWQHUV 35,9$7(6(&7,21 '$7$QDPH7<3(VWULQJ YHKLFOHBOLVW7<3(7$%/(2)5()72OFOBYHKLFOH (1'&/$66OFOBUHQWDO'(),1,7,21 *---------------------------------------------------------------------* * CLASS lcl_rental IMPLEMENTATION *---------------------------------------------------------------------* &/$66OFOBUHQWDO,03/(0(17$7,21 0(7+2'OLIBSDUWQHUVaGLVSOD\BSDUWQHU GLVSOD\BDWWULEXWHV (1'0(7+2'OLIBSDUWQHUVaGLVSOD\BSDUWQHU 0(7+2'FRQVWUXFWRU QDPH LPBQDPH (1'0(7+2'FRQVWUXFWRU 0(7+2'DGGBYHKLFOH $33(1'LPBYHKLFOH72YHKLFOHBOLVW (1'0(7+2'DGGBYHKLFOH 0(7+2'GLVSOD\BDWWULEXWHV '$7$UBYHKLFOH7<3(5()72OFOBYHKLFOH :5,7(LFRQBWUDQVSRUWBSURSRVDO$6,&21QDPH :5,7( +HUHFRPHVWKHYHKLFOHOLVW 8/,1(8/,1( /223$7YHKLFOHBOLVW,172UBYHKLFOH UBYHKLFOH!GLVSOD\BDWWULEXWHV (1'/223 (1'0(7+2'GLVSOD\BDWWULEXWHV (1'&/$66OFOBUHQWDO,03/(0(17$7,21 © SAP AG BC401 10-34 *---------------------------------------------------------------------* * CLASS lcl_travel_agency DEFINITION *---------------------------------------------------------------------* &/$66OFOBWUDYHOBDJHQF\'(),1,7,21 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*LPBQDPH7<3(VWULQJ 0(7+2'6DGGBSDUWQHU,03257,1*LPBSDUWQHU 7<3(5()72OLIBSDUWQHUV 0(7+2'6GLVSOD\BDJHQF\BSDUWQHUV 35,9$7(6(&7,21 '$7$QDPH7<3(VWULQJ SDUWQHUBOLVW7<3(7$%/(2)5()72OLIBSDUWQHUV (1'&/$66OFOBWUDYHOBDJHQF\'(),1,7,21 *---------------------------------------------------------------------* * CLASS lcl_travel_agency IMPLEMENTATION *---------------------------------------------------------------------* &/$66OFOBWUDYHOBDJHQF\,03/(0(17$7,21 0(7+2'GLVSOD\BDJHQF\BSDUWQHUV '$7$UBSDUWQHU7<3(5()72OLIBSDUWQHUV :5,7(LFRQBGHSHQGHQWV$6,&21QDPH :5,7( +HUHDUHWKHSDUWQHUVRIWKHWUDYHODJHQF\ 8/,1(8/,1( /223$7SDUWQHUBOLVW,172UBSDUWQHU UBSDUWQHU!GLVSOD\BSDUWQHU (1'/223 (1'0(7+2'GLVSOD\BDJHQF\BSDUWQHUV 0(7+2'FRQVWUXFWRU QDPH LPBQDPH (1'0(7+2'FRQVWUXFWRU 0(7+2'DGGBSDUWQHU $33(1'LPBSDUWQHU72SDUWQHUBOLVW (1'0(7+2'DGGBSDUWQHU (1'&/$66OFOBWUDYHOBDJHQF\,03/(0(17$7,21 © SAP AG BC401 10-35 (YHQWV &RQWHQWV l 'HILQLQJDQGWULJJHULQJHYHQWV l 5HJLVWHULQJDQGKDQGOLQJHYHQWV SAP AG 2002 © SAP AG BC401 11-1 (YHQWV8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 'HILQHDQGWULJJHUHYHQWV l +DQGOHHYHQWV l 5HJLVWHUDQGGHUHJLVWHUHYHQWV l 5HFHLYHDUHIHUHQFHIURPWKHVHQGHU l ([SODLQWKHFRQFHSWXDOGLIIHUHQFHVEHWZHHQ PHWKRGVDQGHYHQWV SAP AG 2002 © SAP AG BC401 11-2 (YHQWV,QWHJUDWLRQLQ&RXUVH&RQWHQW E A = A CF@G > 7 A 7 9 8 H9 E A = AJI DLK >M = E > =A 8B qsrUtvu1w x n ] h a [ d l ^@a b p l b h\] k n ]o a [ \ h l ] ^ a \] [.\ a ] h a@j Z [ ck [ lm m k Z,[.\ ]^ \ _` a b1c3d3ef g a ^@h i e # # ! " 67 8 9:<; 9= >@? 9 AB C A D B> 7 $ %& & ' ()*,+.- ) + %/10 % (32 * % 0 0 ' ( )4 %5 % N,OP Q.R@SUTWV S Q V X S@Y SAP AG 2002 © SAP AG BC401 11-3 (YHQWV2YHUYLHZ z z}z |~@z PDLQSURJUDP &5($7(2%-(&7UBFDU(;3257,1*... &DU &DUUHQWDOFRPSDQ\ 9HKLFOHUHJLVWUDWLRQRIILFH y{z}|~z << 3<3<<¡¢ SAP AG 2002 n By triggering an event, an object or class announces a change of state, or that a certain state has been achieved. n In the example, the class FDUtriggers the event FUHDWHG. Other classes subscribe to this event (triggered when a car is instantiated) and process it. The car rental company wants to be informed of completion; the car is registered at the vehicle registration office. n Note: The events discussed here are QRWthe events of the ABAP runtime system (such as INITIALIZATION, START-OF-SELECTION, and so on) and QRWthe events of background processing or workflow. © SAP AG BC401 11-4 )HDWXUHV l/RRVHUOLQNDJHWKDQIRUDPHWKRGFDOO 7ULJJHULQJREMHFWPDNHVVWDWXVFKDQJHNQRZQ £ +DQGOHUREMHFWVFDQVKRZLQWHUHVWDQGUHDFW £ l'LIIHUHQWFRPPXQLFDWLRQPRGHO 7KHWULJJHUGRHVQRWNQRZWKHXVHU XVHU VUHDFWLRQLVRIQRLQWHUHVWWRWULJJHU ¤ l$UHDVRIXVH £ ¥ *8,LPSOHPHQWDWLRQV &RQIRUPLW\ZLWKRWKHUREMHFWPRGHOV&20$FWLYH;FRQWUROV2SHQ'RF SAP AG 2002 n Events link objects or classes more loosely than direct method calls do. Method calls establish precisely when and in which statement sequence the method is called. However, with events, the reaction of the object to the event is triggered by the event itself. n Events are most often used in GUI implementations. n Other external object models, such as COM, ActiveX controls, and so on, also provide events. © SAP AG BC401 11-5 7ULJJHULQJDQG+DQGOLQJ(YHQWV2YHUYLHZ 5XOHV l7ULJJHULQJHYHQWV &ODVVGHILQHVHYHQW (9(176&/$66(9(176 § 2EMHFWRUFODVVWULJJHUVHYHQW 5$,6((9(17 ¨ l+DQGOLQJHYHQWV ¦ (YHQWKDQGOHUFODVVGHILQHVDQGLPSOHPHQWVHYHQW © ª KDQGOHUPHWKRG >&/$66@0(7+2'6)25(9(172) ¦ (YHQWKDQGOHUREMHFWRUKDQGOHUFODVVUHJLVWHUVLWVHOIWR VSHFLILFHYHQWVDWUXQWLPH 6(7+$1'/(5 SAP AG 2002 n At the moment of implementation, a class defines its: • Instance events (using the EVENTS statement) • Static events (using the CLASS-EVENTS statement) n Classes or their instances that receive a message when an event is triggered at runtime and want to react to this event define event handler methods. Statement: [CLASS-]METHODS <handler_method> FOR EVENT <event> OF <classname>. n These classes or their instances are registered to one or more events at runtime. Statement: SET HANDLER <handler_method> FOR <reference>. (for instance events) SET HANDLER <handler_method>. (for static events) n A class or instance can trigger an event at runtime using the RAISE EVENT statement. © SAP AG BC401 11-6 'HILQLQJDQG7ULJJHULQJ(YHQWV6\QWD[ &/$66FODVVQDPH!'(),1,7,21 (9(176HYHQW!(;3257,1*9$/8( H[BSDU! 7<3(W\SH! &/$66FODVVQDPH!,03/(0(17$7,21 0(7+2'P! 5$,6((9(17HYHQW!(;3257,1*H[BSDU! DFWBSDU! &/$66OFOBYHKLFOH'(),1,7,21 38%/,&6(&7,21 0(7+2'6FRQVWUXFWRU,03257,1*... § (9(176YHKLFOHBFUHDWHG ... (1'&/$66 FDU &/$66OFOBYHKLFOH,03/(0(17$7,21 0(7+2'FRQVWUXFWRU ... ¨ 5$,6((9(17YHKLFOHBFUHDWHG (1'0(7+2' (1'&/$66 «­¬®W¯J°L±²³®­´±Wµ®¶·¸®¹sº SAP AG 2002 n Both instance and static events can be triggered in instance methods. n Only static events can be triggered in static methods. n Events can only have EXPORTING parameters which must be passed by value. n Triggering an event using the statement RAISE EVENT has the following effect: n • The program flow is interrupted at that point • The event handler methods registered to this event are called and processed • Once all event handler methods have been executed, the program flow continues If an event handler method in turn triggers an event, then the program flow is again interrupted and all event handler methods are executed (nesting). © SAP AG BC401 11-7 +DQGOLQJDQG5HJLVWHULQJ(YHQWV Ð |~@z y{z |~z ÅLÆ ÇÉÈUÊ3ÈËÇ<ÌÉÆÍÈÎÈUÆ Ç@Ï »½¼J¾¿ UHQWDO UHJLVWUDWLRQ RIILFH »¼J¾¸À FDUULHU Á ¾@Âû1Ä ¡<3<3<<1<¢ SAP AG 2002 n Events are registered using the SET HANDLER statement. Registration is only active at program runtime. Events cannot be persistent. n You want to register an object to an event belonging to another object. The SET HANDLER statement enters the registration in that object’s list. All handlers for one event are entered in this list. n When the event is triggered, the list shows which event handler methods need to be called. © SAP AG BC401 11-8 (YHQW+DQGOHU0HWKRGV &/$66FODVVBKDQGOH!'(),1,7,21 0(7+2'6RQBHYHQW!)25(9(17HYHQW! 2)FODVVQDPH!_LQWHUIDFH! ,03257,1*H[BSDU!H[BSDU1!>VHQGHU@ © &/$66OFOBUHQWDO'(),1,7,21 35,9$7(6(&7,21 0(7+2'6DGGBYHKLFOH)25(9(17YHKLFOHBFUHDWHG2)OFOBYHKLFOH ,03257,1*VHQGHU (1'&/$66 FDU UHQWDO DGGBYHKLFOH Ñ ÎÈ<Ò¡ÌLÓÔLÈWÕvÓ<Ê3ÈÖ×dzÈUØ Ù SAP AG 2002 n Event handler methods are triggered by events (RAISE EVENT), although they can also be called like normal methods (CALL METHOD). n The interface of the event handler method consists solely of IMPORTING parameters. You can only use parameters from the definition of the corresponding events (event interface). An event interface, which only has EXPORTING parameters, is defined using the EVENTS statement in the declaration of the event. The parameters are typed in the event definition and the typing is passed to the event handler method, that is, the interface parameters of the event handler method cannot be typed in the definition of the event handler method. In addition to the explicitly defined event interface parameters, the implicit parameter sender can also be listed as an IMPORTING parameter for instance events. This passes on a reference to the object that triggered the event. © SAP AG BC401 11-9 5HJLVWHULQJIRUDQ(YHQW6\QWD[ 6(7+$1'/(5UHIBKDQGOH!!RQBHYHQW! )25UHIBVHQGHU!_)25$//,167$1&(6 >$&7,9$7,21YDU!@ &/$66OFOBUHQWDO'(),1,7,21 ... 35,9$7(6(&7,21 0(7+2'6DGGBYHKLFOH)25(9(17YHKLFOHBFUHDWHG2)... (1'&/$66 ª &/$66OFOBUHQWDO,03/(0(17$7,21 0(7+2'FRQVWUXFWRU ... 6(7+$1'/(5DGGBYHKLFOH)25$//,167$1&(6 (1'0(7+2' (1'&/$66 FDU VHWKDQGOHU UHQWDO «­¬®¯J°É±½²³®­´±Wµ®¶1·¸®¹sº SAP AG 2002 n When an event is triggered, only those event handler methods are executed that have, by this point, registered themselves using SET HANDLER. n You can register an event using ACTIVATION ’X’, and deregister it using ACTIVATION space. If you do not specify ACTIVATION, then the event registers (default behavior). n You can register several methods in one SET HANDLER statement: SET HANDLER <ref_handle1>-><handler_method1> ... <ref_handleN>-><handler_methodN> FOR <ref_sender> | FOR ALL INSTANCES. © SAP AG BC401 11-10 5HJLVWUDWLRQ'HUHJLVWUDWLRQ+DQGOHU7DEOHV ÚÛ¡Ü3<¸¡Ý­ßÞà¡Íá<ר ÊâÕvÓUÖÊ FDU YHKLFOHBFUHDWHG HYHQW 5HJLVWHUHG +DQGOHU REMHFW PHWKRG UHJBYHKLFOH UHJLVWUDWLRQ RIILFH Úãä­U¸¡Ý3åÞàÜæá<קá ʸÕvÓUÖÊ FDU YHKLFOHBFUHDWHG HYHQW 5HJLVWHUHG +DQGOHU REMHFW PHWKRG DGGBYHKLFOH UHJBYHKLFOH UHQWDO UHJLVWUDWLRQ RIILFH SAP AG 2002 n Every object that has defined events has an internal table, the handler table. All objects that have registered for events are entered in this table together with their event handler methods. n Objects that have registered themselves for an event that is still "active" also remain "active". The methods of these objects are called when the event is triggered, even if they can no longer be reached using main memory references. © SAP AG BC401 11-11 (YHQW+DQGOLQJ)HDWXUHV l l l (YHQWKDQGOLQJLVVHTXHQWLDO 6HTXHQFHLQZKLFKHYHQWKDQGOHUPHWKRGVDUHFDOOHGLVQRWGHILQHG :LWKUHJDUGWRWKH*DUEDJH&ROOHFWRUUHJLVWUDWLRQKDVWKHVDPHHIIHFW DVDUHIHUHQFHWRWKHUHJLVWHUHGREMHFW 5HJLVWHUHGREMHFWVDUHQHYHUGHOHWHG ¤ l l 7KHYLVLELOLW\RIDQHYHQWGHILQHVDXWKRUL]DWLRQIRUHYHQWKDQGOLQJ 7KHYLVLELOLW\LQDQHYHQWKDQGOHUPHWKRGGHILQHVDXWKRUL]DWLRQIRU XVLQJ6(7+$1'/(5VWDWHPHQWV ¤ (YHQWKDQGOHUPHWKRGVKRZHYHUFDQRQO\KDYHWKHVDPHYLVLELOLW\RUPRUH UHVWULFWHGYLVLELOLW\WKDQWKHHYHQWVWKH\UHIHUWR SAP AG 2002 n If several objects have registered for an event, then the sequence in which the event handler methods are called is not defined, that is, there is no guaranteed sequence in which the event handler methods are called. n If a new event handler is registered in an event handler method for an event that has just been triggered, then this event handler is added to the end of the sequence and is then also executed when its turn comes. If an existing event handler is deregistered in an event handler method, then this handler is deleted from the event handler method sequence. n Events are also subject to the visibility concept and can therefore be either public, protected, or private. Visibility specifies who can handle an event: n • PUBLIC: All users • PROTECTED: Only users within that class or its subclasses • PRIVATE: Only users within that class Event handler methods also have visibility attributes. Event handler methods, however, can only have the same visibility or more restricted visibility than the events they refer to. The visibility of event handler methods establishes authorization for SET HANDLER statements; SET HANDLER statements can be used: Everywhere, in the class and its subclasses, or only within the class. © SAP AG BC401 11-12 (YHQWV8QLW6XPPDU\ <RXDUHQRZDEOHWR l 'HILQHDQGWULJJHUHYHQWV l +DQGOHHYHQWV l 5HJLVWHUDQGGHUHJLVWHUHYHQWV l ([SODLQWKHFRQFHSWXDOGLIIHUHQFHVEHWZHHQ PHWKRGVDQGHYHQWV SAP AG 2002 © SAP AG BC401 11-13 (YHQWV([HUFLVHV 8QLW(YHQWV 7RSLF7ULJJHULQJDQG+DQGOLQJ(YHQWV At the conclusion of these exercises, you will be able to: • Define and trigger events • Handle events • Register event handler methods As soon as a new airplane is created, this event must be made known to the airline. . 0RGHOVROXWLRQ 6$3%&B(9(6B0$,1B$ 6$3%&B9(+'B+include program 6$3%&B(9(6B$include program 1 The DGGBDLUSODQH method of the class OFOBFDUULHU will no longer be explicitly called in the PDLQSURJUDP, but be triggered automatically from the class OFOBDLUSODQH. Triggering an event when a plane is created (CREATE OBJECT) will result in the automatic execution of the airline method DGGBDLUSODQH. 1-1 In the UML diagram decide what steps are needed where for the triggering and handling of the event DLUSODQHBFUHDWHG. See next page for UML diagram. 1-2 Trigger the event DLUSODQHBFUHDWHG in a suitable method within the class OFOBDLUSODQH. 1-3 Handle the event within the class OFOBFDUULHU using the handler method DGGBDLUSODQH. This method requires a new interface, its implementation must also be changed slightly. 1-4 In the main program, comment out the calls r_carrier->add_airplane. 1-5 In the debugger, check whether the event is triggered and handled by the event handler method when the planes are created. If this does not happen, check whether one of the four important steps for implementing events was perhaps left out. © SAP AG BC401 11-14 2SWLRQDO Implement the event YHKLFOHBFUHDWHG for the car rental company and its corresponding vehicles. 2SWLRQDO DGYDQFHG In the UML, there is the possibility of using events when creating the business partners of the travel agency. If airlines, car rental companies, or hotels are created, these business partners should automatically be made known to the travel agency. 2-1 2-2 © SAP AG You could solve this using the events FDUULHUBFUHDWHG, UHQWDOBFUHDWHG, and KRWHOBFUHDWHG. Would this be problematic? What would be the best solution? Implement your solution for OFOBFDUULHU and OFOBUHQWDO. BC401 11-15 6ROXWLRQV 8QLW 7RSLF (YHQWV 7ULJJHULQJDQG+DQGOLQJ(YHQWV *&---------------------------------------------------------------------* *& Report SAPBC401_EVES_MAIN_A * *& * *&---------------------------------------------------------------------* *& Implement Events in lcl_vehicle and lcl_airplane * *&---------------------------------------------------------------------* REPORT sapbc401_eves_main_a. TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2. INCLUDE <icon>. include sapbc401_vehd_h. INCLUDE sapbc401_eves_a. DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus, r_passenger type ref to lcl_passenger_plane, r_cargo type ref to lcl_cargo_plane, r_carrier type ref to lcl_carrier, r_rental type ref to lcl_rental, r_agency type ref to lcl_travel_agency. START-OF-SELECTION. *######################## ***** Create TRAVEL_AGENCY ************************************** CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’. ***** Create CARRIER ******************************************** © SAP AG BC401 11-16 create object r_carrier exporting im_name = ’Smile&Fly-Travel’. ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. ***** insert planes into itab if client *************************** UBFDUULHU!DGGBDLUSODQH UBSDVVHQJHU UBFDUULHU!DGGBDLUSODQH UBFDUJR ***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_carrier ). ******* create RENTAL ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’. ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’MAN’ im_cargo = 45. UBUHQWDO!DGGBYHKLFOH UBWUXFN ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = ’Mercedes’ im_passengers = 80. UBUHQWDO!DGGBYHKLFOH UBEXV ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’VOLVO’ im_cargo = 48. UBUHQWDO!DGGBYHKLFOH UBWUXFN ***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_rental ). ******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ). © SAP AG BC401 11-17 *&---------------------------------------------------------------------* *& Include SAPBC401_EVES_A * *&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes. HYHQWVDLUSODQHBFUHDWHG PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type TYPE saplane-planetype EXPORTING ex_weight TYPE s_plan_wei ex_tankcap DATA: name TYPE s_capacity. TYPE string, planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS. © SAP AG "lcl_airplane DEFINITION BC401 11-18 *------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. name = im_name. planetype = im_planetype. n_o_airplanes = n_o_airplanes + 1. UDLVHHYHQWDLUSODQHBFUHDWHG ENDMETHOD. "constructor METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap. WRITE: / icon_ws_plane AS ICON, / ’Name of airplane’(001), AT pos_1 name, / ’Type of airplane: ’(002), AT pos_1 planetype. get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ). WRITE: / ’Weight:’(003), weight, ’Tankkap:’(004), cap. ENDMETHOD. "display_attributes METHOD display_n_o_airplanes. WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD. "display_n_o_airplanes METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. ex_weight = 100000. ex_tankcap = 10000. ENDIF. ENDMETHOD. ENDCLASS. © SAP AG "get_technical_attributes "lcl_airplane IMPLEMENTATION BC401 11-19 *---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION *---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. PUBLIC SECTION. "---------------------METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype im_cargo TYPE scplane-cargomax. METHODS: display_attributes REDEFINITION. PRIVATE SECTION. "---------------------DATA: max_cargo TYPE scplane-cargomax. ENDCLASS. "lcl_cargo_plane DEFINITION *---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. METHOD constructor. CALL METHOD super->constructor EXPORTING im_name = im_name im_planetype = im_planetype. max_cargo = im_cargo. ENDMETHOD. "constructor METHOD display_attributes. super->display_attributes( ). WRITE: / ’Max Cargo = ’, max_cargo. ULINE. ENDMETHOD. ENDCLASS. © SAP AG "display_attributes "lcl_cargo_plane IMPLEMENTATION BC401 11-20 *---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION *---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane.. PUBLIC SECTION. METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype im_seats TYPE sflight-seatsmax. METHODS: display_attributes REDEFINITION. PRIVATE SECTION. DATA: max_seats TYPE sflight-seatsmax. ENDCLASS. "lcl_passenger_plane DEFINITION *---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION *---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. METHOD constructor. CALL METHOD super->constructor EXPORTING im_name = im_name im_planetype = im_planetype. max_seats = im_seats. ENDMETHOD. "constructor METHOD display_attributes. super->display_attributes( ). WRITE: / ’Max Seats = ’, max_seats. ULINE. ENDMETHOD. ENDCLASS. © SAP AG "display_attributes "lcl_passenger_plane IMPLEMENTATION BC401 11-21 *---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, DGGBDLUSODQHIRUHYHQWDLUSODQHBFUHDWHGRIOFOBDLUSODQH ,03257,1*VHQGHU display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name TYPE string, airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS. "lcl_carrier DEFINITION *---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner. display_airplanes( ). ENDMETHOD. "lif_partners~display_partner METHOD add_airplane. APPEND sender TO airplane_list. ENDMETHOD. "add_airplane METHOD display_attributes. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD. "display_attributes METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD. © SAP AG "display_airplanes BC401 11-22 METHOD constructor. name = im_name. VHWKDQGOHUDGGBDLUSODQHIRUDOOLQVWDQFHV ENDMETHOD. "constructor METHOD get_name. ex_name = name. ENDMETHOD. ENDCLASS. © SAP AG "get_name "lcl_carrier IMPLEMENTATION BC401 11-23 6ROXWLRQV RSWLRQDO 8QLW 7RSLF (YHQWV 7ULJJHULQJDQG+DQGOLQJ(YHQWV *&---------------------------------------------------------------------* *& Report SAPBC401_EVES_MAIN_B * *& * *&---------------------------------------------------------------------* *& Implement Events in LCL_vehicle and lcl_airplane * *& Implement Events in LCL_carrier and lcl_rental * *&---------------------------------------------------------------------* REPORT sapbc401_eves_main_b. TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2. INCLUDE <icon>. include sapbc401_vehd_i. INCLUDE sapbc401_eves_b. DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus, r_passenger type ref to lcl_passenger_plane, r_cargo type ref to lcl_cargo_plane, r_carrier type ref to lcl_carrier, r_rental type ref to lcl_rental, r_agency type ref to lcl_travel_agency. START-OF-SELECTION. *######################## ******* create travel_agency ***************************************** CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’. ******* create rental ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’. © SAP AG BC401 11-24 ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’MAN’ im_cargo = 45. ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = ’Mercedes’ im_passengers = 80. ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’VOLVO’ im_cargo = 48. ***** Create CARRIER ******************************************** create object r_carrier exporting im_name = ’Smile&Fly-Travel’. ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. ******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ). © SAP AG BC401 11-25 *&---------------------------------------------------------------------* *& Include SAPBC401_EVES_B * *&---------------------------------------------------------------------* *------------------------------------------------------------------* * events in: lcl_airplane and lcl_carrier ! * *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes. EVENTS:airplane_created. PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type TYPE saplane-planetype EXPORTING ex_weight TYPE s_plan_wei ex_tankcap DATA: name TYPE s_capacity. TYPE string, planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS. © SAP AG "lcl_airplane DEFINITION BC401 11-26 *------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. name = im_name. planetype = im_planetype. n_o_airplanes = n_o_airplanes + 1. RAISE EVENT airplane_created. ENDMETHOD. "constructor METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap. WRITE: / icon_ws_plane AS ICON, / ’Name of airplane’(001), AT pos_1 name, / ’Type of airplane: ’(002), AT pos_1 planetype. get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ). WRITE: / ’Weight:’(003), weight, ’Tankkap:’(004), cap. ENDMETHOD. "display_attributes METHOD display_n_o_airplanes. WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD. "display_n_o_airplanes METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. ENDMETHOD. ENDCLASS. ex_weight = 100000. ex_tankcap = 10000. ENDIF. "get_technical_attributes "lcl_airplane IMPLEMENTATION ... © SAP AG BC401 11-27 *---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane FOR EVENT airplane_created OF lcl_airplane IMPORTING sender, PRIVATE SECTION. "----------------------------------DATA: name TYPE string, airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS. "lcl_carrier DEFINITION *---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ). ENDMETHOD. "lif_partners~display_partner METHOD add_airplane. APPEND sender TO airplane_list. ENDMETHOD. "add_airplane METHOD display_attributes. skip 2. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD. "display_attributes METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD. © SAP AG "display_airplanes BC401 11-28 METHOD constructor. name = im_name. SET HANDLER add_airplane FOR ALL INSTANCES. 5$,6((9(17OLIBSDUWQHUVaSDUWQHUBFUHDWHG ENDMETHOD. "constructor ENDCLASS. "lcl_carrier IMPLEMENTATION *&---------------------------------------------------------------------* *& Include SAPBC401_VEHD_i * *&---------------------------------------------------------------------* *---------------------------------------------------------------------* * define client lcl_travel_agency * it will use the interface lif_partners * * implement EVENT in LCL_VEHICLE and LCL_RENTAL *---------------------------------------------------------------------* ,17(5)$&(OLIBSDUWQHUV 0(7+2'6GLVSOD\BSDUWQHU HYHQWGHILQHGLQVLGHWKHLQWHUIDFH (9(176SDUWQHUBFUHDWHG (1',17(5)$&(OLIBSDUWQHUV *---------------------------------------------------------------------* * CLASS lcl_vehicle DEFINITION *---------------------------------------------------------------------* CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. "------------------METHODS: get_average_fuel IMPORTING im_distance TYPE s_distance im_fuel TYPE ty_fuel RETURNING value(re_avgfuel) TYPE ty_fuel. METHODS constructor IMPORTING im_make TYPE string. METHODS display_attributes. METHODS set_make IMPORTING im_make TYPE string. METHODS get_make EXPORTING ex_make TYPE string. CLASS-METHODS get_count EXPORTING re_count TYPE i. EVENTS: vehicle_created. PRIVATE SECTION. "------------------DATA: make TYPE string. METHODS init_make. © SAP AG BC401 11-29 CLASS-DATA: n_o_vehicles TYPE i. ENDCLASS. "lcl_vehicle DEFINITION *---------------------------------------------------------------------* * CLASS lcl_vehicle IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION. METHOD get_average_fuel. re_avgfuel = im_distance / im_fuel. ENDMETHOD. "get_average_fuel METHOD constructor. make = im_make. ADD 1 TO n_o_vehicles. raise event vehicle_created. ENDMETHOD. "constructor METHOD set_make. IF im_make IS INITIAL. init_make( ). " me->init_make( ). also possible ELSE. make = im_make. ENDIF. ENDMETHOD. "set_make METHOD init_make. make = ’default make’. ENDMETHOD. "init_make METHOD get_make. ex_make = make. ENDMETHOD. "get_make METHOD display_attributes. WRITE: make. ENDMETHOD. "display_attributes METHOD get_count. re_count = n_o_vehicles. ENDMETHOD. ENDCLASS. © SAP AG "get_count "lcl_vehicle IMPLEMENTATION BC401 11-30 *---------------------------------------------------------------------* * CLASS lcl_rental DEFINITION *---------------------------------------------------------------------* CLASS lcl_rental DEFINITION. PUBLIC SECTION. "------------------METHODS: constructor IMPORTING im_name TYPE string. 0(7+2'6DGGBYHKLFOHIRUHYHQWYHKLFOHBFUHDWHGRIOFOBYHKLFOH LPSRUWLQJVHQGHU METHODS display_attributes. INTERFACES: lif_partners. PRIVATE SECTION. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS. "lcl_rental DEFINITION *---------------------------------------------------------------------* * CLASS lcl_rental IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ). ENDMETHOD. METHOD "lif_partners~display_partner constructor. name = im_name. set handler add_vehicle for all instances. UDLVHHYHQWOLIBSDUWQHUVaSDUWQHUBFUHDWHG ENDMETHOD. METHOD "constructor add_vehicle. APPEND sender TO vehicle_list. ENDMETHOD. © SAP AG "add_vehicle BC401 11-31 METHOD display_attributes. DATA: r_vehicle TYPE REF TO lcl_vehicle. skip 2. WRITE: / WRITE: icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE. LOOP AT vehicle_list INTO r_vehicle. r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD. "display_attributes ENDCLASS. "lcl_rental IMPLEMENTATION *---------------------------------------------------------------------* * CLASS lcl_travel_agency DEFINITION *---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION. PUBLIC SECTION. "------------------METHODS: constructor IMPORTING im_name TYPE string. 0(7+2'6DGGBSDUWQHUIRUHYHQWSDUWQHUBFUHDWHGRIOLIBSDUWQHUV ,03257,1*VHQGHU METHODS display_agency_partners. PRIVATE SECTION. "------------------DATA: name TYPE string, partner_list TYPE TABLE OF REF TO lif_partners. ENDCLASS. "lcl_travel_agency DEFINITION *---------------------------------------------------------------------* * CLASS lcl_travel_agency IMPLEMENTATION *---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION. METHOD display_agency_partners. DATA: r_partner TYPE REF TO lif_partners. WRITE: icon_dependents AS ICON, name. WRITE: ’ Here are the partners of the travel agency: ’.ULINE.ULINE. LOOP AT partner_list INTO r_partner. r_partner->display_partner( ). ENDLOOP. ENDMETHOD. © SAP AG "display_agency_partners BC401 11-32 METHOD constructor. name = im_name. VHWKDQGOHUDGGBSDUWQHUIRUDOOLQVWDQFHV ENDMETHOD. METHOD "constructor add_partner. $33(1'VHQGHU72SDUWQHUBOLVW ENDMETHOD. ENDCLASS. © SAP AG "add_partner "lcl_travel_agency IMPLEMENTATION BC401 11-33 *OREDO&ODVVHVDQG,QWHUIDFHV &RQWHQWV l /RFDOYHUVXVJOREDOFODVVHVDQGLQWHUIDFHV l &ODVV%XLOGHU SAP AG 2002 © SAP AG BC401 12-1 *OREDO&ODVVHVDQG,QWHUIDFHV8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 'HVFULEHWKHGLIIHUHQFHEHWZHHQORFDODQGJOREDO FODVVHVDQGLQWHUIDFHV l &UHDWHJOREDOFODVVHVDQGLQWHUIDFHVXVLQJWKH &ODVV%XLOGHU SAP AG 2002 © SAP AG BC401 12-2 *OREDO&ODVVHVDQG,QWHUIDFHV,QWHJUDWLRQLQ &RXUVH&RQWHQW E A > A CF G ? 7 A 7 I: 9 H: E A > AKJ DL ?M > E ? >A 9B |= ~ |1 U vxw y{z1| w} w |U~ ~U ~ tu a ] k b q] ka [ eo ^ a b s o b k\] n q ]3r a [ \ k o ]^ a \] [.\ a ] k a m Z[ dIn [ op p n Z,[.\ ]I^ \ _3` acbKd3e3fhgji a ^ck l f " " ! 687 9 :;=< :> ? @ : AB C A D B? 7 #%$& & ' ()*,+.- ) + $ /1$ 5 0 $ $ (32 * $ 0 0 ' ( )4 N%OPIQ RSUTWV S Q V X S Y SAP AG 2002 © SAP AG BC401 12-3 *OREDO&ODVVHVDQG,QWHUIDFHV &ODVV%XLOGHU &ODVV%XLOGHU :RUNLQJZLWKJOREDOFODVVHVDQGLQWHUIDFHV :RUNLQJZLWKJOREDOFODVVHVDQGLQWHUIDFHV $SSOLHGH[DPSOH $SSOLHGH[DPSOH SAP AG 2002 © SAP AG BC401 12-4 5HYLHZ/RFDO&ODVVHVDQG,QWHUIDFHV 3URJUDPP 3URJUDPP 5(3257SURJ 5(3257SURJ &/$66OFOBDLUSODQH'(),1,7,21 ... (1'&/$66 '$7$UBDLUSODQH 7<3(5()72OFOBDLUSODQH ... ... l /RFDOSURJUDPFODVVHV /RFDOFODVVHVDUHRQO\YLVLEOHLQWKHSURJUDPWKH\ZHUHGHILQHGLQ 1RJOREDODFFHVVSRVVLEOH 1RWVWRUHGLQWKH5HSRVLWRU\QRZKHUHXVHGOLVWDQGVRRQ SAP AG 2002 n Local classes and interfaces are only known within the program in which they are defined and implemented. n Local classes and interfaces are not stored in the Repository (no TADIR entry). There is no "global" access to these classes or interfaces (for example, from other programs). © SAP AG BC401 12-5 *OREDO&ODVVHVDQG,QWHUIDFHV l l $%$3:RUNEHQFKGHYHORSPHQWWRRO j= 7RROIRUFUHDWLQJWHVWLQJDQGPDQDJLQJJOREDOFODVVHVDQG LQWHUIDFHV 6WRUHGLQ5HSRVLWRU\ l l l *HQHUDWHVWKHIUDPHZRUNFRGLQJ IRUH[DPSOH&/$66QDPH!'(),1,7,21 0DQDJHVWKHLQFOXGHSURJUDPVLQZKLFKWKHFRGLQJLVVWRUHG $FFHVVIURPDOOSURJUDPVXVLQJ7<3(5()72 &XVWRPHUQDPHVSDFHIRUJOREDOFODVVHVDQGLQWHUIDFHV< RU = :KHUHXVHGOLVWDYDLODEOH SAP AG 2002 n Unlike local program classes and interfaces, global classes and interfaces can be created and implemented using the ABAP Workbench tool &ODVV%XLOGHU. These classes and interfaces are then available active throughout the whole system. n Global class and interface names share the same namespace. n Individual methods of global classes and interfaces can be transported separately. © SAP AG BC401 12-6 &UHDWLQJ*OREDO&ODVVHVLQWKH2EMHFW1DYLJDWRU Workbench Edit Goto Utilities Environment MIME Repository =¡£¢¥¤K¦{§¡¨¥=§ Repository Browser ©¥§3ª«¬=¨­®¯¬¨ª«¥¬U¨ Repository Information System Tag Library Transport Organizer °±² ³´±µI¶ ·%¸%¹»º¼I½¾¼ ¼ Object Name ·,¸»¹%º¼I½¾¼¼ ¹hÅ ±cÆcÆ=ÇÈ ÉI ±IÂ Ê ¹Å ± Æ Æ¶cÆ System Help ¿»¶ À Á à &UHDWHDFODVVLQWKH2EMHFW 1DYLJDWRU ,QVWDQFHFUHDWLRQ SULYDWH SURWHFWHG ¦{ «¥©­Ä¬ DEVWUDFW Description 1RUPDO$%$3FODVV ([FHSWLRQFODVV 3HUVLVWHQWFODVV )LQDOFODVV 2QO\PRGHOHG SAP AG 2002 n You can also display the Class Builder’s global classes in the Object Navigator. n Being able to view classes through the navigation window on the left is especially useful when developing code. n Here, you can also create a new class. Proceed as you would when creating a program: Use the context menu for a package node or directly for a class node within a package. n Alternatively, you can also create a new class by entering a class name and then choosing 'LVSOD\. In this case, you must specify a package. n I dialog box asks you to make further specifications for the new class: é Instance creation: Where are instances of this new class to be created? For example, if you specify SULYDWH the class could only be instantiated within the class itself. The default setting is SXEOLF. é Exception class (this will be discussed in more detail later, in the context of exception handling) é Persistent class (this will be discussed in more detail later, in the context of special techniques) é Final class (represents the end of an inheritance tree) é Only modeled (class definition only for modeling) © SAP AG BC401 12-7 &ODVV%XLOGHU$WWULEXWHV Class Edit Goto Utilities Environment System 'HILQHFODVV DWWULEXWHV Help ËÌ­´{UKÍÎÏ{ÐÑÒÔÓÕÖ{×ØÚÙ´ÛÝÜÞÖ{ØÚßÚàá×ãââ ø ó,ë8ë éhÿ,ë8æèíð æ¯éí ø ó8ëë.ÿæ åWí ñóå í é þ å»íæjî å8ë ö,ì û ÿ8æñåWí ñóå8ë öì­ò ! ! híî å»ÿ»ê»ë ô þ ø å»ôåWÿ8æñå%ê" ì#æjî ÷»å ìææèíî ïWðæ¯å3ë ä¥å8æèç%éhê»ë ÷»å»ÿ,æñë ÿ8æñåWíÿ%ó»ø üýhþ å3ë ì¥ø î óë»åë hî ø æñåí ì ææíî ïWð,æñå = òó%ôõå ö8ì ò ü ò%ì û öì­ò %ö å3÷»å»ø .ÿ8ë,æñóÿ .ÿ8ë,æñóÿ æ ó8æèî ùî ëî ï,ú äéWêhú û å%ú íjî ÷ íjî ÷ íjî ÷ üýhþ üýhþ üýhþ üýhþ å î ÿ å å ì=ë8ë%é,ú ü»ýhþ å üû . ò ì öìò å8ëíî þ jæ î éÿ òó%ôõåéó»î í þ ø óWÿ,å ì­î í þ ø óÿ%åæ ýhþ å òUð»ôï,åWíhéó»î í þ ø óWÿ,å8ë SAP AG 2002 n In the Class Builder, choosing the $WWULEXWHV tab displays the class attributes and their properties (instance attribute/static attribute and the visibility area) © SAP AG BC401 12-8 &ODVV%XLOGHU0HWKRGV Class Edit Goto Utilities Environment System Help 'HILQHFODVV PHWKRGV ËÌ­´{UKÍÎÏ{ÐÑÒÔÓÕÖ{×ØÚÙÛÚÜÞÖÎØÚß àÞ×{ââ ö%ìI û öì­ò! ! ø ó8ëë ÿ8æñåWí ñóå F1<G8)1 ,=; )E- . +/,0)1 B<3DC*)E- @1=; ) +*A - &å þ æèî é hóWí.ó»ôå8æ¯å»íë ä¥å8æjç,éhê»ë û % ü û ­ ò ü ö8ì ì ühüû H % ü ö8ì ò»ì û ö8ì ò 9, ,<1=; >?,0) ä¥å8æjç,éhê»ë éÿ3ë%æjíðæ éí ô þ ø åôåWÿæ å%ê" ì#æèî ÷»å '(*)*+, - ÿ,ë ö%åI÷åø ù=î ëWî ïWî ø î æ ý ÿ8ë,æ ó ÿ å ä¥å8æèç%éhêJ ðhï»ø î ÿ8ë,æ ó ÿ å ä¥å8æèç%éhêJ ðhï»ø î æ¯óæjî äå8æèç,éhê ðhï»ø î . +/,0)*12+*3 465 7 8*)/-:94 ; 3/-/)/- äéWêú äå8æ¯ú å8ëíî þ æèî éÿ ­ò$ ü û % ü û ì¥î í þ ø óÿ%åó3æñæjíèî ïhðæñå8ë ò=ð%ô{ï,åWíWé þ ø óÿ,åë 'HILQHVLJQDWXUHRIVHOHFWHG PHWKRG KHUH&216758&725 SAP AG 2002 n Under the 0HWKRGVtab, you can create methods. n This task is simplified by the &RQVWUXFWRUfunction, choosing which automatically creates the constructor method. You still have to specify the interface and the source code for the method. n Choose 3DUDPHWHUto define the signature for the method the cursor is currently on. © SAP AG BC401 12-9 &ODVV%XLOGHU,QWHUIDFH0HWKRGV Class Edit Goto Utilities Environment System Help ËÌ­´{UKÍÎÏ{ÐÑÒÔÓÕÖ{×ØÚÙÛÚÜÞÖÎØÚß àÞ×{ââ ö%ìI û öì­ò! ! ø ó8ëë ÿ8æñåWí ñóå F1<G8)1 ,=; )E- . +/,0)1 B<3DC*)E- @1=; ) +*A - &å þ æèî é hóWí.ó»ôå8æ¯å»íë ä¥å8æjç,éhê»ë û % ü û ­ ò ü ö8ì ì ühüû H % ü ö8ì ò»ì û ö8ì ò Khö L ü ì ûü 9, ,212; >?/,0) ä¥å8æjç,éhê»ë ô þ ø åôåWÿæ å%ê" ì#æèî ÷»å '(*)*+, - ÿ,ë ùî ë»î ïî ø î æ ý ö%åI÷åø ÿ8ë,æ óÿ å ä¥å8æèç%éhêJ ðhï»ø î ÿ8ë,æ óÿ å ä¥å8æèç%éhêJ ðhï»ø î æ¯óæjî äå8æèç,éhê ðhï»ø î h ð ïWø î ÿ8æñåWí ñóåõä¥å8æèç%éhê 0HWKRGLPSOHPHQWDWLRQRI DJOREDOLQWHUIDFH . +/,0)*12+*3 465 7 8*)/-:94 ; 3/-/)/- ä¥éWêú äå8æ¯ú å8ëíî þ æèî éÿ ò ü û % ü û ì­î í þ ø óÿ%åóææèíjî ïhð3æ¯å8ë òUð»ôï,åWíhé þ ø óÿ%å3ë í å þ óíñóæèî éÿ,M ë éhíWë,æñóíæ $QQRXQFHDJOREDO LQWHUIDFHLQDJOREDOFODVV SAP AG 2002 n A global interface that was created in the Class Builder can be announced in a server class by choosing the ,QWHUIDFHV tab. n All interface methods are then automatically listed under the 0HWKRGV tab. n All interface methods must then be implemented in this server class. In the example, the interface zif_fly consists of a single method start. © SAP AG BC401 12-10 &ODVV%XLOGHU0HWKRG,QWHUIDFH Class Edit Goto Utilities Environment System Help ÔÌ¥3=KÍÎÏ{Ð{ÑÒËÓÕÖ{×ØÚÙÛÚÜÞÖ{ØÚßÝàÞ×ãââ ø ó8ëë ÿ8æñåWí ñóå F1 G8 )1 ,=; )E- ä­å,æèç%éhêRhó%í¯ó8ô å3æñåWí.ë ä¥å8æèç%éhê%ë WóWíó»ôå8æñåí # ä òhì N ä I ä P ö8ì ò ü K ö8ì û ö3ì¥ò!*! . +/,0)*1 B<3/C/)D@ 12; ) +*A - 9, ,012; >?/,0)E- éÿ8ë,æèíð3æ éí ô þ ø å»ôåhÿæ å%ê" ìS8æèî ÷»å '() +/, ä­å8æjç,éhê%ë . +/,0)*12+*3 465 7 8*)/- 94 ; 3D-)D- ¥ò üû% ü û &3å þ æèî éÿ,ë üýhþ üýWþ üýWþ üýWþ üýWþ å ìëë»é%ú ü%ýþ å ü û ò ì ö3ì¥òPQñú ú ú å å î ÿ å å ñóðhø æWùKó»ø ðåOåë,íî þ æèî éÿ ø ó»ÿ%åæ ýWþ å 6LJQDWXUHSDUDPHWHUVRI PHWKRG KHUH&216758&725 SAP AG 2002 n Selecting a method and choosing 3DUDPHWHUV displays a list of all the method’s signature parameters. © SAP AG BC401 12-11 &ODVV%XLOGHU0HWKRG,PSOHPHQWDWLRQ Method Edit Goto Utilities Environment System Help j3{= Í{Ï{ÐÑÕ£´ÓÕÖÎ×Ø ÙjÛÚÜÞÖ{ØÚßÝàÞ×ãââ üýþ å WóWíó»ôå8æñåíë ä# òì äM ä#K öì­ò ü ä¥å8æjç,éhê Uî ÿ%ó3æðíå üýhþ å¥ë þ å % ú å3ë»íèî þ æèî éÿ ü ü û $ ò ü X ì ö ì òQ= ö8ì ò ü ]ø óÿ%åæ ýWþ å ¥ò$ üû % ü û ó æî ÷»å äN üT Uéÿ8ë,æèíðæ¯éí ú ôõó VåMWÎî ôXÿóôå»ú þ ø óWÿ8/å »æ ýþ å Wî ô þ ø óÿ%å3æ ýþ å»ú ì ZY ü /ÿ hé[óWî í þ ø ó»ÿ%åëú ü T [ ú ò \ ä 'LVSOD\WKHLQWHUIDFHWR KHOSZLWKLPSOHPHQWLQJ 'LVSOD\WKHLQWHUIDFHWRKHOS WKHPHWKRG ZLWKLPSOHPHQWLQJWKHPHWKRG SAP AG 2002 n When implementing methods, you can also display the signature of the method to aid your work. n In this example (constructor), the signature consists of the import parameters im_make and im_planetype. © SAP AG BC401 12-12 &ODVV%XLOGHU,QKHULWDQFH Class Edit Goto Utilities Environment System Help ^ ËÌ­´{UKÍÎÏ{ÐÑÒ áÖ× àZ_ ÙÖ{à $QQRXQFHVXSHUFODVV ø ó8ëë.ÿæ åWí ñóå í é þ å»íæjî å8ë ö ì û SK ö8ì ò!! ÿ8æñåWí ñóå8ë híî å»ÿ»ê»ë ø ó,ë8ë éhÿ,ë8æèíð æ¯éí ô þ ø å»ôåWÿ8æñå%ê" ì#æjî ÷»å ìæñæèíî ïWð8æ å3ë ä¥å8æèç%éhê»ë ÿ8æñåWíÿ%ó»ø üýhþ å3ë ÷»å»ÿ,æñë ì¥ø î óë»åë 6XSHUFODVV 6XSHUFODVV 6XSHUFODVV =&/B$,53/$1(B Description Instantiation Final SAP AG 2002 n In the Class Builder, inheritance relationships are defined by choosing the 3URSHUWLHVtab. n Here, for example, is the 6XSHUFODVVfunction, which you can use to specify the superclass for the current class. n In this example, the superclass ZCL_AIRPLANE_00 is specified for the subclass ZCL_CARGO_PLANE_00. © SAP AG BC401 12-13 &ODVV%XLOGHU7HVW(QYLURQPHQW {|}~ }}P M#P ` aÆ Ã ±6aI² ¶ jWÀÀ ¶Â k ÇÁDl ¶ Â3¹»±cÆ ¶dh² Ã.È m ¶ Handler ·¹Ç¾Ed` ¿W°,ÇndPfi ¾¼¼ dWà à ÂñÈ /É oà ¶cÆ p ¶c<à q /Á rIÆ b` c»°8Ç6de3¾f¾/g»¾DdK` ¿W°,ÇhdKfi*c Class Edit Goto Utilities {K|}~ }P}ZSK\ NI s¶cÆà g Éut ¶ ² à v w Handler j»ÀÀ¶  k Ç ÁEl ¶IÂI¹W±cƶdh²cÃñÈ m ¶ ·¹hǾDdP` ¿W°,ÇndPfi ¾¼ ¼ ` aà ¶  z ± ² ¶cÆ dWà Ã.ÂÈ DÉ o à ¶ Æ p¶cà qEÁ r3Æ ºExhy¹WÇ´¾DdP` ¿°,ÇndKfi¾3¼ ¼ b` c»°Çnde3¾EdPs/s¿` ¸js i/c b` »c °Çnd3e ¾*f ¾D g ¾6d` ¿°,Çhdfi*c &UHDWHDQLQVWDQFHZLWK WKHWHVWHQYLURQPHQW SAP AG 2002 n If the class is completed and activated, you can use the test tool to create an instance of the class and test method calls of the class. © SAP AG BC401 12-14 *OREDO&ODVVHVDQG,QWHUIDFHV &ODVV%XLOGHU &ODVV%XLOGHU :RUNLQJZLWKJOREDOFODVVHVDQGLQWHUIDFHV :RUNLQJZLWKJOREDOFODVVHVDQGLQWHUIDFHV $SSOLHGH[DPSOH $SSOLHGH[DPSOH SAP AG 2002 © SAP AG BC401 12-15 *OREDO&ODVVHVLQWKH2EMHFW1DYLJDWRU Workbench ¸¹º¸º» · Edit Goto Utilities Environment System ¶E³0´§P¼½ ¦¾´§³¿K¶¥SÀÁ´ Pattern MIME Repository =¡£¢¥¤K¦{§¡¨¥=§ Repository Browser ©¥§3ª«¬=¨­®¯¬¨ª«¥¬U¨ Repository Information System Tag Library Transport Organizer ¹Å ±cÆ nÆ k ` a à ¶I z ±² ¶ ·8¹hǾDdK` ¿»°,Çndfi¾3¼ ¼ Object ·¹Ç¾EdPName ` ¿W°,ÇndPfi ® ® ® ¯ ¯ ¯ Help ¾¼ ¼ dWà à ÂÈ É/oà ¶cÆ fd$pi f ¾/g ¾Ed` ¿W°,ÇndPfi*c °,ÇndKfK i ¾/s6h e ° i p ¶cà q Á/Ir Æ ¹gfc3s ¿»j ¹s/g ¿ b` » c °ÇEd3e ¾dss ¿` ¸js*ic b` » c °ÇEd3e ¾*f ¾/» g ¾dK` ¿W°,ÇndKfi*c ¿%¶ ÀIÁ3Â.à ¬hr¶E­KÁ d²cÃñÈ m ¶ /HIW'LVSOD\LQJDFODVVLQWKH ¢¥S ª °=² ±¥N ª ³.² ´¥ ¢ µxX ¢ ¶[´Xµ DOORZV\RX WRDFFHVVWKHFODVVFRPSRQHQWV Description Class Airplane e Name of airplane Number of planes Airplane type *KK*KK* $P/¡¢ £¤¡¥¦ §P¨DK© Dª¨E©« CONSTRUCTOR Displays airplane attributes Displays number of airplanes 5LJKW(GLWDQ$%$3SURJUDP ¶6 ³2´§ LQWKH· SAP AG 2002 n You can also display the Class Builder’s global classes in the Object Navigator. n Being able to view classes through the navigation window on the left is especially useful when editing source code. You can drag & drop specific components into the right Editor window and automatically create and insert source code (as a template). © SAP AG BC401 12-16 &ODVV%XLOGHU&5($7(2%-(&7 Workbench ¸º¹º¸U» · Edit Goto Utilities Environment System Help ¶¥E³=´­§P¼½¦R´¥§³¿¶¥SÀÁ´ Pattern ¿»¶ ÀÁ3 à ¬ur3¶D­1Á dh² ÃÈ m¶ =¡£¢¥¤K¦{§¡¨¥=§ Repository Browser 6HOHFWLQJDQGGUDJJLQJLQWR ©¥§3ª«¬=¨­®¯¬¨ª«¥¬U¨ Repository Information WKH(GLWRUFUHDWHV System <  Â0 Â< Â0 Â< Â0 Â< Â0 Â0 Â< Â< Â0 Â0 Â< Â< Â0 Â0 Â< Â< Â0 Â0 Â< Â< Â2 Â< Â< Â< Â2 Â< Â< Â< Â2 Â< Â<  Âà e¾¼ ¼è¾3± È Â.À3Å E± a¶ Tag Library &5($7(2%-(&7 Â< Â0 Â< Â0 Â< Â0 Â< Â0 Â0 Â< Â< Â0 Â0 Â< Â< Â0 Â0 Â< Â< Â0 Â0 Â< Â< Â2 Â< Â< Â< Â2 Â< Â< Â< Â2 Â< Â<  Transport Organizer Âà e¾¼ ¼è¾3± È Â.À3Å E± a¶ ¹Å ±cÆ nÆ k ` a à ¶I z ±² ¶ ¹h6Ç dPc*cÅ ²IÅ ¾3± È Â.À3Å D± a ¶ biÄD` f` s*` gfÅ ·8¹hÇD¾ dK` ¿»°,nÇ dfi¾3¼ ¼ cs6d¿sv gÄ/v ciÇi3¹s*` gfÅ MIME Repository ÆhÆ6ÆnÆnÆ6ÆnÆnÆhÆ6ÆnÆnÆ6ÆnÆnÆhÆ6ÆnÆnÆ6Æ Object ·¹Ç¾EdPName ` ¿W°,ÇndPfi ® ® ® ¯ ¯ ¯ ¾¼ ¼ dWà à ÂÈ É/oà ¶cÆ fd$pi f ¾/g ¾Ed` ¿W°,ÇndPfi*c °,ÇndKfK i ¾/s6h e ° i p ¶cà q Á/Ir Æ ¹gfc3s ¿»j ¹s/g ¿ b` » c °ÇEd3e ¾dss ¿` ¸js*ic b` » c °ÇEd3e ¾*f ¾/» g ¾dK` ¿W°,ÇndKfi*c Description Class Airplane e &5($7(2%-(&7UBDLUSODQH (;325,1* ,03257,1* Name of airplane Number of planes Airplane type CONSTRUCTOR Displays airplane attributes Displays number of airplanes SAP AG 2002 n n 'UDJ GURS the class name: Instantiates an object. 6HOHFWLQJDQGGUDJJLQJ a class name WRWKHULJKW automatically creates a CREATE OBJECT statement with the whole interface of the constructor. You still have to add the call’s actual parameters. © SAP AG BC401 12-17 &ODVV%XLOGHU&$//0(7+2' Workbench ¸¹º¸º» · Edit Goto Utilities Environment System ¶E³0´§P¼½ ¦¾´§³¿K¶¥SÀÁ´ Pattern MIME Repository =¡£¢¥¤K¦{§¡¨¥=§ Repository Browser ©¥§3ª«¬=¨­®¯¬¨ª«¥¬U¨ Repository Information System Tag Library 6HOHFWLQJDQGGUDJJLQJLQWR Transport Organizer ¹ Å ±cÆ Ænk ` a à ¶I z ±² ¶ ·8¹hǾDdK` ¿»°,Çndfi¾3¼ ¼ Object ·8¹hǾEName d` ¿»°,Çndfi ® ® ® ¯ ¯ ¯ Help ¾3¼ ¼ WKH(GLWRUFUHDWHV&$// 0(7+2' dhà Ã.ÂÈ É/oà ¶cÆ fdp$i f ¾/»g ¾DdK` ¿»°,Çndfic °,ÇndfU i ¾/sEW e ° i p ¶ à q Á/r Æ ¹gfcs ¿»j ¹sg ¿ b` » c °8Ç6de ¾dPs/s ¿` ¸js ic b` » c °8Ç6de ¾ 3f ¾» g ¾dP` ¿W°,ÇndPfi*c ¿»¶ ÀÁ3 à ¬ur3¶D­1Á dh² ÃÈ m¶ ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇEÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇEÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/Ç Ç¾È/ÉhÊËDËÌÊÍ/Î/ÏuÐ ÑDÍEÒ/Ó ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇEÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/ÇEÇDÇ/ÇDÇ/ÇDÇDÇ/ÇDÇ/ÇDÇDÇ/Ç Ç¾È/ÉhÊËDËÌÊÍ/Î/ÏuÐ ÑDÍEÒ/Ó Ô ÑEÍ*ÕDÕÖÑ Ô ÑÖÍ/ÎDÏuÐÑEÍDÒ/ÓÖ×/ÓØDÎEÒÎ/ÙDÎEÚDÒ ÛEÜÞÝ ß*Ü àuá/âà6Ûnã/ä6ã*å/Ü*æhánçè éDéDé/éDé/éDéDé/éDé/éDéEé/éDéDé/éDé/éDéDé/éDé/éDéDé/éDé/éDéDé/éEé ¹ Description Å ±´ÆÆd È ÂÀIÅ ±EaI¶ ¶ &$//0(7+2' [[[!GLVSOD\BDWWULEXWHV Name of airplane Number of planes Airplane type CONSTRUCTOR Displays airplane attributes Displays number of airplanes SAP AG 2002 n n 'UDJ GURS the method name: Calls a method 6HOHFWLQJDQGGUDJJLQJ a method WRWKHULJKW automatically creates a CALL METHOD statement with the whole interface of the method. In this case you must also add the call’s actual parameters and set the call’s reference variable. © SAP AG BC401 12-18 *OREDO&ODVVHVDQG,QWHUIDFHV &ODVV%XLOGHU &ODVV%XLOGHU :RUNLQJZLWKJOREDOFODVVHVDQGLQWHUIDFHV :RUNLQJZLWKJOREDOFODVVHVDQGLQWHUIDFHV $SSOLHGH[DPSOH $SSOLHGH[DPSOH SAP AG 2002 © SAP AG BC401 12-19 6$3*ULG&RQWURO M³ñª¯Ä 륢X¶ ê ´§³ î´R³ñªÄ ë¥ÄE³¯U§ U´Xµx¢Ä²´­ª#¶ » §¢R³ ¦{Īìí°ª§3ªU¢¾³ 7RROEDU $$ $$ $$ $$ /+ /+ /+ /+ /+ 86' 86' 86' 86' '(0 '(0 '(0 '(0 '(0 $ $ $ $ $ $ $ SAP AG 2002 n An applied example for the use of ABAP Objects is the standard output tool 6$3*ULG&RQWURO. It is implemented in ABAP Objects and provides the user with a wide range of functions (for example sorting data, reorganizing/hiding columns, totalling). n Principle of 6$3&RQWURO)UDPHZRUN: To use such a control the developer no longer has to re-implement functions in the control, but simply specify the instances of the classes that contain these functions. n The exact procedure for using the SAP Grid Control will be discussed in the following. © SAP AG BC401 12-20 ,QFOXGLQJD*ULG&RQWURO,QVWDQFHLQD'LDORJ3URJUDP <RXUHTXLUHWZRFODVVHVIRU XVLQJD6$3*ULG&RQWURO 6FUHHQ $UHD ï öEP % % ü ¥äS ¥ò ü ì ò û &XVWRP &RQWDLQHU &RQWURO $/9 *ULG &RQWURO Public Private ð ö/ % »ì ö8ùP û < Public Private SAP AG 2002 n To implement a SAP Grid Control, you must implement: é An instance of the container control é An instance of the displaying SAP Grid Control é The data retrieval é The display of data using a method call n An SAP container is capable of housing other controls (such as the SAP Grid Control, tree control, picture control, splitter control, and so on). It manages these controls in a logical collection and provides a physical area for visualization. Each control "lives" in a container. Because containers are themselves controls, containers can be nested within one another. The container becomes the SDUHQW of its control. n Global classes are available for accessing the custom control and the SAP Grid Control. At runtime, an object each of the class &/B*8,B&86720B&217$,1(5 and the class &/B*8,B$/9B*5,' is created. These objects contain all necessary information for accessing the controls. For information on the object types (classes) and the corresponding methods, refer to the online documentation. © SAP AG BC401 12-21 'LVSOD\LQJ'DWDZLWKD*ULG&RQWURO,QVWDQFH ... '$7$FRQWDLQHUBU7<3(5()72FOBJXLBFXVWRPBFRQWDLQHU JULGBU7<3(5()72FOBJXLBDOYBJULG ñ ²IÅ ¾3µ*oÈ ¾3²Eo Æà Á ­ Å Å Å ... &5($7(2%-(&7FRQWDLQHUBU (;3257,1*FRQWDLQHUBQDPH &217$,1(5B ... &5($7(2%-(&7JULGBU (;3257,1*LBSDUHQW FRQWDLQHUBU ... Public Private ñ ² Å ¾µ*oÈ ¾I±IÅ mc¾µ8Â.È r Public Private JULGBU!VHWBWDEOHBIRUBILUVWBGLVSOD\ LBVWUXFWXUHBQDPH 6$3/$1( LWBRXWWDE LWDEBVDSODQH ... alv_grid_control öö öö öö öö ÷ø ÷ø ÷ø ÷ø ÷ø òó òó òó ôõ õùù õùù õùù õùú õùú ú ù ù ù ûù ò ûò ó ú ù ù ù ûù ú ûú ù ú ù ù ù ûù ü ûò ò ú ù ù ù ûù ý ûò þ ú ù ù ù ûù ò ûò ü ú ù ù ù ûù ú ûú ô ú ù ù ù ûù ü ûú ò ú ù ù ù ûù ü ûù õ ú ù ù ù ûù ý ûú ÿ ýòü ôþ ýòü ôþ ýòü ôþ üôþ ùù òúüõ ýô òúüõ ýô òúüõ ýô òúüõ ýô òúüõ ýô ö üúò ö üúò ó õ ó ûõ ù ù ó õ ó ûõ ù ù ö ü ò ù ûü ù ù ö ü ò ù ûü ù ù ö ü ò ù ûü ù ù ö üòþ ö üòþ SAP AG 2002 n The control is displayed on a screen, the call of which is not shown in this example. n To create the object that communicates with the container control, it is sufficient to include the name of the container area &217$,1(5B on the screen, on which the container area is defined. n To create the object that communicates with the SAP Grid Control, you must include the reference variable that refers to the object for the custom container. This is because the object for the SAP Grid Control contains a reference variable that points to the container object as a private attribute. This relationship tells the object, which container it should be included in. n To display data in a SAP Grid Control, it must be provided in an internal table. Then a method is called that receives the content of the internal table and its structure. The name of this method id VHWBWDEOHBIRUBILUVWBGLVSOD\. If, while the program runs, only the content of the internal table to be displayed changes, it is sufficient to call the method UHIUHVKBWDEOHBGLVSOD\ with the container area before the the screen is re-sent. © SAP AG BC401 12-22 *OREDO&ODVVHVDQG,QWHUIDFHV8QLW6XPPDU\ <RXDUHQRZDEOHWR l 'HVFULEHWKHGLIIHUHQFHEHWZHHQORFDODQGJOREDO FODVVHVDQGLQWHUIDFHV l &UHDWHJOREDOFODVVHVDQGLQWHUIDFHVXVLQJWKH &ODVV%XLOGHU SAP AG 2002 © SAP AG BC401 12-23 ([HUFLVHV 8QLW*OREDO&ODVVHVDQG,QWHUIDFHV 7RSLF&UHDWLQJ*OREDO&ODVVHV At the conclusion of these exercises, you will be able to: • Use the Class Builder to process global classes and interfaces A travel agency communicates with its business partners. Various hotels are now also to be business partners. 0RGHOVROXWLRQ &/B+27(/ &/B+286( ,)B3$571(56 1-1 Create the global class =&/BB+27(/ in the Class Builder. 1-2 The class is to have the followingattributes: QDPH type STRING, private instance attribute PD[BEHGV type I, private instance attribute QBRBKRWHO type I, private static attribute 1-3 The class is to have the followingmethods: FRQVWUXFWRU with import parameters LPBQDPH and LPBEHGV GLVSOD\BDWWULEXWHV for displaying the instance attributes of the class GLVSOD\BQBRBKRWHOV static method for displaying instances created 1-4 Implement these methods. 1-5 Activate and test your class using the Class Builder test tool. © SAP AG BC401 12-24 2 Define the global interface =,)BB3$571(56 with the interface method GLVSOD\BSDUWQHU. Implement the interface in the class =&/BB+27(/. 3 2SWLRQDO Include the new class in the program with the airlines and car rental companies. Adjust the sections that refer to the local interface OLIBSDUWQHUV to suit the new global interface. OFOBWUDYHOBDJHQF\ XVHV ]LIBSDUWQHUV LPSOHPHQWV OFOBFDUULHU OFOBKRWHO OFOBYHKLFOHV OFOBDLUSODQH 4 OFOBFDUBUHQWDO RSWLRQDO Define an inheritance relationship in the Class Builder. Your hotel is to inherit from the superclass =&/BB+286(. Tip: Construct the class =&/BB+286( copying the class =&/BB+27(/ to =&/BB+286( and then making changes to this copy. The house should only have an attribute QDPH (protected) and the method GLVSOD\BDWWULEXWHV; delete all superfluous components. Finally, define the inheritance relationship between the house and the hotel. © SAP AG BC401 12-25 6ROXWLRQV 8QLW 7RSLF *OREDO&ODVVHVDQG,QWHUIDFHV &UHDWLQJ*OREDO&ODVVHV *&---------------------------------------------------------------------* *& Report SAPBC401_CLSS_MAIN_A * *&---------------------------------------------------------------------* *& Global Class lcl_hotel is also a business partner of the * *& travel agency * *&---------------------------------------------------------------------* REPORT sapbc401_clss_main_a. TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2. INCLUDE <icon>. include sapbc401_vehd_j. INCLUDE sapbc401_clss_a. DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus, r_passenger type ref to lcl_passenger_plane, r_cargo type ref to lcl_cargo_plane, r_carrier type ref to lcl_carrier, r_rental type ref to lcl_rental, r_agency type ref to lcl_travel_agency, UBKRWHOW\SHUHIWRFOBKRWHO START-OF-SELECTION. *######################## ******* create travel_agency ***************************************** CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’. ******* create rental ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’. © SAP AG BC401 12-26 ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’MAN’ im_cargo = 45. ***** Create CARRIER ******************************************** create object r_carrier exporting im_name = ’Smile&Fly-Travel’. ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. ******* create hotel ***************************************** FUHDWHREMHFWUBKRWHOH[SRUWLQJLPBQDPH +2/,'$<,11 LPBEHGV ******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ). © SAP AG BC401 12-27 6SHFLDO7HFKQLTXHV &RQWHQWV l $EVWUDFWDQGILQDOFODVVHV l 9LVLELOLW\RIFRQVWUXFWRUV l )ULHQGV l 2EMHFW6HUYLFHV SAP AG 2002 © SAP AG BC401 13-1 6SHFLDO7HFKQLTXHV8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l &UHDWHDQGGHVFULEHDEVWUDFWDQGILQDOFODVVHV l ([SODLQWKHYLVLELOLW\FULWHULDRIFRQVWUXFWRUV l 'HVFULEHWKHIULHQGFRQFHSW l 'HVFULEHWKHSHUVLVWHQFHVHUYLFHRI2EMHFW 6HUYLFHV SAP AG 2002 © SAP AG BC401 13-2 6SHFLDO7HFKQLTXHV,QWHJUDWLRQLQ&RXUVH&RQWHQW E A > A CFG ? 9 A 9 ; : H; E A > AJI DLK ?M > E ? >A :B z# wyx{zU|~} # z |~y } p ] j a [ d n^ a b v `c f n ` s `n b b a b n ] l t/u a ] j b p] ja [ dn ^ a b s n b j \] m p ]+q a [r\ j n ] ^ a \] [\ a ] j al Z [ c m [ no o m Z[\ ]^ \ _+` a b3c5d5egfih a ^j k e $ $ ! #" 89 : ;+<#= ;+> ?@ ; AB C A D B? 9 % &' ' ( )+*-,/.0 * . &132 & )54 , & 2 2 ( ) *-6 &7 & N/OP QRSUTWV S Q V X SY SAP AG 2002 © SAP AG BC401 13-3 6SHFLDO7HFKQLTXHV $EVWUDFWDQGILQDOFODVVHV $EVWUDFWDQGILQDOFODVVHV 9LVLELOLW\RIFRQVWUXFWRUV 9LVLELOLW\RIFRQVWUXFWRUV 7KHIULHQGFRQFHSW 7KHIULHQGFRQFHSW 3HUVLVWHQWREMHFWV 3HUVLVWHQWREMHFWV SAP AG 2002 © SAP AG BC401 13-4 $EVWUDFW&ODVVHV l $EVWUDFWFODVVHVWKHPVHOYHVFDQQRWEHLQVWDQWLDWHG DOWKRXJK WKHLUVXEFODVVHVFDQ 5HIHUHQFHVWRDEVWUDFWFODVVHVFDQUHIHUWRLQVWDQFHVRIVXEFODVVHV l $EVWUDFW LQVWDQFH PHWKRGVDUHGHILQHGLQWKHFODVVEXWQRW LPSOHPHQWHG 7KH\PXVWEHUHGHILQHGLQVXEFODVVHV &/$66OFOBYHKLFOH'(),1,7,21$%675$&7 38%/,&6(&7,21 0(7+2'6HVWLPDWHBIXHOBFRQVXPSWLRQ$%675$&7 ,03257,1* (1'&/$66 &ODVVFDQQRW EHLQVWDQWLDWHG 0HWKRGQRW LPSOHPHQWHGLQWKLV FODVV SAP AG 2002 n It is not possible to instantiate objects of an abstract class However, this does not mean that references to such a class are not useful. On the contrary, they are very useful, since they can (and must) refer to instances in subclasses of the abstract class at runtime. The CREATE OBJECT statement is extended in this context. You can specify the class of the instance to be created explicitly: CREATE OBJECT <RefToAbstractClass> TYPE <NonAbstractSubclassName>. n Abstract classes are normally used as an incomplete blueprint for concrete (that is, non-abstract) subclasses, for example to define a uniform interface. n Abstract instance methods are used to specify particular interfaces for subclasses, without having to immediately provide implementation for them. Abstract methods need to be redefined and thereby implemented in the subclass (here you also need to include the corresponding redefinition statement in the DEFINITION part of the subclass). n Classes with at least one abstract method are themselves abstract. n Static methods and constructors cannot be abstract (they cannot be redefined). © SAP AG BC401 13-5 )LQDO&ODVVHV l )LQDOFODVVHVFDQQRWKDYHVXEFODVVHV &/$66OFOBWUXFN'(),1,7,21),1$/ ,1+(5,7,1*)520OFOBYHKLFOH (1'&/$66 g ii ... l ... ... )LQDOPHWKRGVFDQQRWEHUHGHILQHGLQVXEFODVVHV &/$66OFOBEXV'(),1,7,21,1+(5,7,1*)520OFOBYHKLFOH 38%/,&6(&7,21 0(7+2'6HVWLPDWHBQXPEHUBRIBIUHHBVHDWV),1$/ (1'&/$66 SAP AG 2002 n A final class cannot have subclasses, and can protect itself in this way against (uncontrolled) specialization. n A final method in a class cannot be redefined in a subclass, and can protect itself in this way against (uncontrolled) redefinition. n Some features: • A final class implicitly only contains final methods. In this case, you cannot enter FINAL explicitly for these methods. • Methods cannot be both final and abstract. • Classes, on the other hand, that are both abstract and final can be useful: Only static components can be used. © SAP AG BC401 13-6 6SHFLDO7HFKQLTXHV $EVWUDFWDQGILQDOFODVVHV $EVWUDFWDQGILQDOFODVVHV 9LVLELOLW\RIFRQVWUXFWRUV 9LVLELOLW\RIFRQVWUXFWRUV 7KHIULHQGFRQFHSW 7KHIULHQGFRQFHSW 3HUVLVWHQWREMHFWV 3HUVLVWHQWREMHFWV SAP AG 2002 © SAP AG BC401 13-7 :KR&DQ,QVWDQWLDWH&ODVVHV" l 7KHXVDELOLW\RIFODVVHVFDQEHUHVWULFWHG &/$66FOBFODVV'(),1,7,21 &5($7(38%/,& (YHU\XVHU FOLHQW FDQFUHDWHLQVWDQFHVRIDFODVV GHIDXOWVHWWLQJ &5($7(3527(&7(' 2QO\WKHFODVVLWVHOIDQGDOOLWVVXEFODVVHVFDQFUHDWHLQVWDQFHVRIWKLV FODVV &5($7(35,9$7( 2QO\WKHFODVVFDQFUHDWHLQVWDQFHVRILWVHOI l 7KLVLPSOLFLWO\FRQWUROVWKHYLVLELOLW\RIWKH FODVV l 3RVVLEOHXVH ¡5¢£¤{ FRQFHSW ±~²L³L´µ{¶ OFOBVLQJOHWRQ Public Private ¥§¦ ¨© ªg«¬ ­ ® ¯ ­ L° ¯ SAP AG 2002 n n If you want to ensure that not every user (client) can instantiate a class, you can use the following additions to restrict the visibility area of the constructor and hence limit the use of the class. (The following additions must be preceded by CLASS ... DEFINITION.) • The CREATE PUBLIC addition is implicitly available for every class definition, provided neither of the other two CREATE additions is used. It defines the default that HYHU\ user can create instances of a known class. • The optional additions CREATE PROTECTED and CREATE PRIVATE, on the other hand, have the effect that not every user can create instances of a class. In the case of CREATE PROTECTED, only VXEFODVVHV of the class or the class itself and, in the case of CREATE PRIVATE, RQO\WKHFODVVLWVHOI can create instances of the class. • Therefore, the additions CREATE PROTECTED and CREATE PRIVATE allow you to control instance creation and, for example, are a prerequisite for the instance management of persistent objects, for which the uniqueness of objects must be ensured. (Persistent objects will be discussed in more detail later.) If it is to be impossible to instantiate a class more than once (for example, because it serves as a data administrator or data container), you can use the singleton concept. The class is defined with the addition CREATE PRIVATE and FINAL and instantiated using its static constructor. A public static component could then make the reference to the class available to an external user. © SAP AG BC401 13-8 6SHFLDO7HFKQLTXHV $EVWUDFWDQGILQDOFODVVHV $EVWUDFWDQGILQDOFODVVHV 9LVLELOLW\RIFRQVWUXFWRUV 9LVLELOLW\RIFRQVWUXFWRUV 7KHIULHQGFRQFHSW 7KHIULHQGFRQFHSW 3HUVLVWHQWREMHFWV 3HUVLVWHQWREMHFWV SAP AG 2002 © SAP AG BC401 13-9 )ULHQGV l ,QUDUHFDVHVFODVVHVKDYHWRZRUNWRJHWKHUFORVHO\DQGPDNHDOO WKHLUFRPSRQHQWVLQFOXGLQJWKHSURWHFWHGDQGSULYDWHRQHV DYDLODEOHWRHDFKRWKHU (IILFLHQWGLUHFWDFFHVVWRWKHGDWDRIDFODVVSURYLGLQJ IULHQGVKLS · · ÜÞÝ#ßàUÝá ´ · 0HWKRGVWKDWDFFHVVWKHVDPHGDWDFDQWKHUHIRUHEHVSUHDGRYHU VHYHUDOFODVVHV 3DFNDJHFUHDWLRQVXSSRUW ÜÞäç{è ³ åæ´-éëê ä ³L´#µæåyé-ìæ³Lí ÂiÃ5ÄÅ Æ½Å Ç½È ÅrÉ Ê-ËÍÌÎÇJÏJÐgÌiÐ ¸#¹3º»½¼¿¾/À¹½ºUÁ½¾ ã{ä ³L´µyå Ñ Ò ÓÅ Æ½Å Ç½È ÅrÉ Ê-ËÌÎǽÈiÐÍÆgÌÔ-ÕiÖ ×UØÍÙUÚ ¾ Ù À{¸U¹Uºg»J¼¾ » Ù ¾Ày¸#¹½º»½¼¿¾ Û Ù ¹ Ù ¾ Ù À{¸U¹Uºg»J¼¾ ãæä ³L´µ{å ârââ SAP AG 2002 n In rare cases, classes have to work together so closely that they need access to their protected and private components. To avoid making these components available to all users, there is the concept of friendship between classes. n A class can provide friendship to other classes and interfaces (and hence all classes that implement the interface). To do this you use the )5,(1'6additions to the CLASS statement, in which all classes and interfaces that are to be provided friendship are listed. Friends are allowed to access the protected and private components of the class providing the friendship and can always create instances of this class, regardless of the CREATE addition to the CLASS statement. n In principle, providing friendship is one-sided: A class providing friendship is not automatically a friend of its friends. If a class providing friendship wants to access the non-public components of a friend, this friend has to explicitly provide friendship to it. n Classes that inherit from friends and interfaces that contain a friend as a component interface also become friends. Therefore, extreme caution is advised when providing friendship. The higher up a friend is in the inheritance tree, the more subclasses can access all components of a class providing friendship. However, providing friendship, unlike the attribute of being a friend, is not inherited. A friend of a superclass is therefore not automatically a friend of its subclasses. © SAP AG BC401 13-10 6SHFLDO7HFKQLTXHV $EVWUDFWDQGILQDOFODVVHV $EVWUDFWDQGILQDOFODVVHV 9LVLELOLW\RIFRQVWUXFWRUV 9LVLELOLW\RIFRQVWUXFWRUV 7KHIULHQGFRQFHSW 7KHIULHQGFRQFHSW 3HUVLVWHQWREMHFWV 3HUVLVWHQWREMHFWV SAP AG 2002 © SAP AG BC401 13-11 3HUVLVWHQFH6HUYLFH $%$3SURJUDP î ä5Ý µæéU³L´-µæ¶ ç{ïWð ´ ß ¶é 3HUVLVWHQFHVHUYLFH ñ ´ Ý åUòó ä ³L¶´ ç{ïWð ´ ß ¶ é 'DWDEDVH Ü ´ ä é³ é-¶´#µy¶~å Ý ¶ Ý ³ µ ¶ Ý-ï L² ´é SAP AG 2002 n The persistence service helps the programmer to work object-oriented with data in relational databases. n In principle, ABAP programs work with data and objects that exist(s) in the internal session at runtime. They are transient when the program is stopped. If this data is to be stored programindependently, that is persistently, it must be stored in the database. (You could also use files on operating system level.) n In ABAP Objects, this is done using the OPEN SQL interface. To be able to work with ABAP Objects persistently, the SHUVLVWHQFHVHUYLFH was introduced with SAP R/3 Basis Release 6.10. Objects and their attributes can be written to the database and reimported. © SAP AG BC401 13-12 )HDWXUHVRIWKH3HUVLVWHQFH6HUYLFH l 2EMHFWVRIDUXQQLQJ$%$3SURJUDPDUH £õôö¡÷æ¢Uø£ l 7KHSHUVLVWHQFHVHUYLFHDOORZV\RXWRZRUNZLWKù l 3HUVLVWHQWFODVVHVDUHFUHDWHG LQWKH&ODVV%XLOGHU ¢Uô÷æú÷¡£+¢Uø£ REMHFWV &UHDWH&ODVV&/B3(56,67(17B&/$66 Class Type Normal ABAP Class Exception Class 3HUVLVWHQW&ODVV ... l 3HUVLVWHQFHVHUYLFHWDVNV /RDGLQJWKHREMHFWVIURPWKHGDWDEDVH · · · 0DQDJLQJFKDQJHVWRWKHREMHFWV 6WRULQJWKHREMHFWVLQWKHGDWDEDVH SAP AG 2002 n To use the persistence service for objects, their classes must be created as so-called SHUVLVWHQW FODVVHVin the Class Builder. n The term SHUVLVWHQWFODVV indicates that the objects of the class and their state are managed by the persistence service. In ABAP programs, objects of these classes are, for example, not created using the normal statement CREATE OBJECT, but instead using a method of the persistence service that ensures the correct initialization. n When creating a persistent class, the Class Builder automatically creates a corresponding class, the so called FODVVDFWRUor DJHQW, the methods of which are used to manage the objects of the persistent class. n As well as their unique identity, persistent classes can also contain so-called key attributes, which the persistence service uses to ensure the uniqueness of the persistent objects’ contents. © SAP AG BC401 13-13 &ODVV$JHQW l :LWKLQWKHSHUVLVWHQFHVHUYLFHWKHFODVVDFWRURU û WKHSHUVLVWHQWREMHFWV · · ö÷÷üöæø¢#ý£ PDQDJHV 7KHDJHQWSURYLGHVDUDQJHRIVHUYLFHV PHWKRGV ZKLFKDUHXVHGWR PDQDJHWKHREMHFWVDQGWKHHQFDSVXODWHGGDWD 7HFKQLFDOO\WKHDJHQWLVDVLQJOHWRQZKLFKLVDGGUHVVHGXVLQJWKHSXEOLF VWDWLFDWWULEXWH$*(17 ... '$7$UBFDUULHU7<3(5()72FOBFDUULHU UBDJHQW7<3(5()72FDBFDUULHU FDUUQDPH7<3(VBFDUUQDPH UBDJHQW FDBFDUULHU !DJHQW 7KHDJHQW DVLQJOHWRQRIWKHFODVV &$B&$55,(5DQG IULHQGRIWKHSHUVLVWHQW FODVV&/B&$55,(5 75< UBFDUULHU UBDJHQW!JHWBSHUVLVWHQW LBFDUULG /+ FDUUQDPH UBFDUULHU!JHWBFDUUQDPH :5,7( /+ FDUUQDPH &$7&+F[BRVBREMHFWBQRWBIRXQG (1'75< SAP AG 2002 n For every persistent class cl_persistent, the Class Builder generates two further classes ca_persistent and cb_persistent. These classes make up the class-specific part of the persistence service. n ca_persistent is the so-called FODVVDFWRU(or agent), which is used to manage the managed object of the class cl_persistent, and in which all actual database accesses take place. The class actor inherits the relevant methods from the abstract superclass cb_persistent. The programmer can extend the class actor and redefine the methods (especially the database accesses). The superclass cb_persistent cannot be changed. The class actor is a friend of the managed class. It has the attribute CREATE PRIVATE and exactly one instance of the class actor is created when it is first accessed. n The static attribute AGENT is a reference variable with the type of the class ca_persistent. When the attribute is first accessed in an ABAP program, the static constructor of the class ca_persistent creates exactly one instance of this class, which points to the attribute AGENT. This object is part of the persistence service and its methods are used to manage the object of the persistent class. For each program there is only one object of the class ca_persistent, because you cannot create objects from outside using CREATE OBJECT. n The class actor manages one or more objects of the relevant persistent class. These objects must have different keys. © SAP AG BC401 13-14 6SHFLDO7HFKQLTXHV8QLW6XPPDU\ <RXDUHQRZDEOHWR l &UHDWHDQGGHVFULEHDEVWUDFWDQGILQDOFODVVHV l ([SODLQWKHYLVLELOLW\FULWHULDRIFRQVWUXFWRUV l 'HVFULEHWKHIULHQGFRQFHSW l 'HVFULEHWKHSHUVLVWHQFHVHUYLFHRI2EMHFW 6HUYLFHV SAP AG 2002 © SAP AG BC401 13-15 ([HUFLVHVRSWLRQDO 8QLW6SHFLDO7HFKQLTXHV 7RSLF6LQJOHWRQ&ODVVHV At the conclusion of these exercises, you will be able to: • Create a singleton; requirement for next exercise 0RGHOVROXWLRQ &/B6,1*/(721 6$3%&B63&6B0$,1B$ 1 2 $GYDQFHG Create the global class =&/BB6,1*/(721 in the Class Builder. The following must be specified for the class: 1-1 You must be able to be instantiate the class only once. (Tip: Instantiation should take place automatically when the class is first accessed.) 1-2 Instantiation only takes place within the class. 1-3 The class has a static reference variable UBVLQJOHWRQ that refers to the instantiated object. 1-4 The class has a static reference variable UBVLQJOHWRQ that refers to the instantiated object. In the main program =%&BB0$,1B63(&,$/, instantiate the singleton class =&/BB6,1*/(721 by calling the JHWBVLQJOHWRQ method. 2-1 Why must the JHWBVLQJOHWRQ method in this example be static? 2-2 Verify your blueprint by calling JHWBVLQJOHWRQ several times. (Debug.) When does instantiation take place and how often? © SAP AG BC401 13-16 ([HUFLVHVRSWLRQDO 8QLW6SHFLDO7HFKQLTXHV 7RSLF&RQFOXGLQJ3URMHFW([HUFLVH At the conclusion of these exercises, you will be able to: • Create a “friends” relationship and access the data of a class providing the friendship (a singleton) from the befriended class (Note that the friends concept is mainly used in bigger projects with more complex classes) 0RGHOVROXWLRQ &/B$*(1&< 6$3%&B63&6B0$,1B% 3 $GYDQFHG Use your singleton and the main program from the last exercise. 3-1 3-2 4 Add a static attribute FRQQHFWLRQBOLVW (with type TY_CONNECTIONS, that is an itab) to the singleton class. When instantiating the singleton, this internal table is to be automatically filled with the flight connections from the table SPFLI. Create a global class =&/BB$*(1&<, which is to be provided friendship by the singleton. 4-1 Define and implement a constructor for =&/BB$*(1&<. In the constructor, the private attribute of the class QDPH is to be initialized. 4-2 This class is to have a public method JHWFRQQHFWLRQ. 4-2-1 Import parameter: LPBFDUULG and LPBFRQQLG (types: S_CARR_ID and S_CONN:ID) 4-2-2 Export parameter: A structure with line type SPFLI Name the export parameter H[BFRQQHFWLRQ. © SAP AG BC401 13-17 4-2-3 In the method, the internal table of the class providing the friendship is to be accessed in a single record access. (READ TABLE...) If the requested record does not exist, it is sufficient in this example to display an appropriate message using the WRITE statement. 5 6 Go back to the singleton class. Here, provide friendship to the class =&/BB$*(1&<. In your main program, instantiate the class =&/BB$*(1&<. The singleton should have been instantiated in the last exercise. There, the internal table with the flight connections is already filled. 6-1-1 Execute the JHWBFRQQHFWLRQ method of =&/BB$*(1&< requesting a flight connection that exists in the SPFLI table. (for example ‚LH‘ / ‚0400‘) IULHQG OFOBDJHQF\ FOBVLQJOHWRQ JHWB FRQQHFWLRQ FRQQHFWLRQB OLVW © SAP AG BC401 13-18 6ROXWLRQVRSWLRQDO 8QLW 7RSLF 6SHFLDO7HFKQLTXHV 6LQJOHWRQ&ODVVHV *&---------------------------------------------------------------------* *& Report SAPBC401_spcS_MAIN_A * *&---------------------------------------------------------------------* *& Work with singleton: *& The singleton class consists of a static pointer r_singleton *& pointing to the class itself; the class is final and has *& the attribute „create private“. *& in the class-constructor the class is instantiated via *& this reference. The static method get_singleton passes the *& reference to the outside world so that the singleton can be used! *&---------------------------------------------------------------------* REPORT sapbc401_spcs_main_a. '$7$UBVLQJOHW\SHUHIWRFOBVLQJOHWRQ START-OF-SELECTION. *######################## UBVLQJOH FOBVLQJOHWRQ !JHWBVLQJOHWRQ © SAP AG BC401 13-19 6ROXWLRQVRSWLRQDO 8QLW 7RSLF 6SHFLDO7HFKQLTXHV &RQFOXGLQJ3URMHFW([HUFLVH *&---------------------------------------------------------------------* *& Report SAPBC401_spcS_MAIN_B * *&---------------------------------------------------------------------* *& Practice with singleton & friends (show package concept ) *& *& The class cl_agency is a friend of the singleton; *& cl_agency works directly with the private data of the singleton *& the method get_connection reads single records out of an *& internal table of the singleton; so the singleton acts as a kind *& of data-container. cl_agency uses this data in the singleton *& directly. (performance aspects, package-concept...) *&---------------------------------------------------------------------* REPORT sapbc401_spcs_main_b. '$7$UBVLQJOHW\SHUHIWRFOBVLQJOHWRQ UBDJHQF\W\SHUHIWRFOBDJHQF\ UHFW\SHVSIOL START-OF-SELECTION. *######################## UBVLQJOH FOBVLQJOHWRQ !JHWBVLQJOHWRQ FUHDWHREMHFWUBDJHQF\H[SRUWLQJLPBQDPH $JHQF\ UBDJHQF\!JHWBFRQQHFWLRQ H[SRUWLQJLPBFDUULG /+ LPBFRQQLG LPSRUWLQJH[BFRQQHFWLRQ UHF ZULWHUHFFDUULGUHFFRQQLG © SAP AG BC401 13-20 ([FHSWLRQ+DQGOLQJ &RQWHQWV l 3UHGHILQHGH[FHSWLRQVDQGH[FHSWLRQV\RXGHILQH \RXUVHOI l 5DLVLQJKDQGOLQJDQGSDVVLQJDORQJH[FHSWLRQV SAP AG 2002 © SAP AG BC401 14-1 ([FHSWLRQ+DQGOLQJ8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l &UHDWH\RXURZQH[FHSWLRQFODVVHV l 5DLVHH[FHSWLRQVLQDSURJUDP l +DQGOHH[FHSWLRQV l 3DVVH[FHSWLRQVDORQJ SAP AG 2002 © SAP AG BC401 14-2 ([FHSWLRQ+DQGOLQJ,QWHJUDWLRQLQ&RXUVH&RQWHQW {}|!~!!, U 0 E A = A CF@G > 6 A 6 : 8 H: E A = AJI DLK >M = E > =A 8B w _ a ^ \ o `x a ^ r ] \ yz a b o ^ a b q] ka [ e v `d g o ` s `o b b a b o ] m t7u a ] k b q] ka [ eo ^ a b s o b k\] n q ]2r a [ \ k o ] ^ a \] [\ a ] k am Z [ d9n [ op p n Z7[\ ]^ \ _2` acb0d2e2fhgji a ^ k l f " " ! 57698 :;!< := >@? :9AB C A9D B > 6 #$% % & '(*),+- ( + $.0$4 / $ $ '21!) $ / / & '(*3 NO7P9Q RSUTWV S Q V@X S@Y SAP AG 2002 © SAP AG BC401 14-3 &ODVV%DVHG([FHSWLRQV2YHUYLHZ ([FHSWLRQFODVV HLWKHUSUHGHILQHG RUGHILQHGE\\RX F[BH[FHSWLRQ ¤¦¥ §¨!©¡ 5$,6((;&(37,217<3(F[BH[FHSWLRQ >(;3257,1*DWWU DWWU @ ([FHSWLRQKDQGOLQJ ([FHSWLRQUDLVHG HLWKHULQ$%$3 VWDWHPHQWRUE\ UXQWLPHV\VWHP ¡U¢£ SAP AG 2002 n We use the term H[FHSWLRQ to refer to a situation that arises while an ABAP program is being executed, where there is no point in continuing to run the program in the normal way. Since SAP R/3 Basis Release 6.10, exceptions and exception handling is based on the exception classes concept. This concept includes the functions of the concepts that preceded it but also enhances (and thus replaces) them. n Class-based exceptions are raised either using the ABAP statement RAISE EXCEPTION or by the ABAP runtime environment. For example, if the program tries to divide by zero the runtime environment raises the exception. You can, however, ascertain that this situation has arisen using a query in the ABAP program. From there, you can then raise an exception yourself. n You can define exception classes yourself, but there is already a range of predefined exception classes in the system. In an exception situation, an exception is represented by an exception object that is, an instance of an exception class. The attributes of each exception object can contain information about the error situation. n The use of class-based exceptions is not limited to object-oriented contexts. Class-based exceptions can be raised and handled in all ABAP processing blocks. In particular, the catchable runtime errors used until now can be handled as class-based exceptions. n If a class-based exception occurs, the system interrupts the normal program flow and tries to navigate to a suitable handler. If it cannot find a handler, a runtime error occurs. © SAP AG BC401 14-4 ([FHSWLRQ&ODVVHV7KH,QKHULWDQFH+LHUDUFK\ F[BURRW ªj«h¬ªc­ ® ¯ «U° ±¡«J² ³0«0°°@­ ® ´´µ´ ¶ «¡ªµ³·ª¢«W¬ª ¶ «¡ªµ³·¸¹ºJ°¼»¡«½³*¾¹0¸J­ ª@­ ¹*± F[BQRBFKHFN F[BG\QDPLFBFKHFN F[BV\BDULWKPHWLFBHUURU F[BVWDWLFBFKHFN F[BV\BPRYHBFDVWBHUURU F[BV\BDULWKPHWLFBRYHUIORZ SAP AG 2002 n All exception classes are derived from the one of the classes CX_NO_CHECK, CX_DYNAMIC_CHECK, or CX_STATIC_CHECK, themselves derived from the common superclass CX_ROOT. The way in which exception classes are assigned to one of these three paths in the hierarchy defines how the associated exceptions are passed along. (This will be discussed in more detail later in this unit.) n All exception classes begin with the prefix CX_. In general, they are defined globally in the ABAP Workbench &ODVV%XLOGHU. However you can also define local exception classes. n The root class CX_ROOT contains two predefined methods that are inherited by the other classes. The GET_SOURCE_POSITION method returns the program name, include name (if relevant), and line number in the source code where the exception occurred. The GET_TEXT method returns an exception text of a class in the form of a string. You can assign several texts to each class. You can then specify which text is to used when an exception is raised by passing an identifier to the IMPORTING parameter TEXTID of the instance constructor. n All exception classes inherit the KERNEL_ERRID attribute from CX_ROOT. This attribute contains the name of the appropriate runtime error if the exception was raised by the runtime environment such as COMPUTE_INT_ZERODIVIDE if the program tries to divide by zero. If the exception is not listed, a runtime error occurs. © SAP AG BC401 14-5 +DQGOLQJ([FHSWLRQV 75< &$7&+F[BF[B>,172UBH[F@ &$7&+F[B>,172UBH[F@ &/($183 Code whose exceptions (if any) are to be handled Handlers Handlers for for the the specified specified exception exception classes classes DQG their DQG their subclasses subclasses (1'75< Block for "tidying up" if there is no handler available in the TRYENDTRY structure SAP AG 2002 n Like all ABAP control structures, TRY-ENDTRY structures can be nested. Thus the TRY block, CATCH- blocks, and the CLEANUP block in particular can contain complete TRY-ENDTRY structures themselves. n The TRY block contains the application code that is to handle the exceptions. If an exception occurs in the TRY block the system searches first for a CATCH statement (which will handle the exception) in the same TRY-ENDTRY structure and then step by step outwards in all the enclosing TRYENDTRY structures. If it finds one, it navigates to this handler. If it cannot find a handler but the TRY-ENDTRY structure is in a procedure, it then tries to pass the exception along to the calling program. (This will be discussed in more detail later.) n A CATCH block contains the exception handler that is executed if a specified exception has occurred in the TRY block in the same TRY-ENDTRY structure. After the CATCH statement, you can specify as many exception classes as you wish. In this way, you define an exception handler for all these exception classes and their subclasses. After an exception occurs, the system searches through the listed exception handlers in the order specified. It then executes the first exception handler whose CATCH statement contains the relevant exception class or one of its superclasses. n In some cases, the system cannot find a handler for an exception within a specific TRY-ENDTRY structure but the exception is handled in a surrounding TRY-ENDTRY structure or passed along to a calling program. If this occurs, a CLEANUP block is executed before leaving the TRY-ENDTRY structure. © SAP AG BC401 14-6 ([DPSOH+DQGOLQJD3UHGHILQHG([FHSWLRQ 3$5$0(7(56LQW7<3(L LQW7<3(L ,IDQRYHUIORZHUURURFFXUVWKH UXQWLPHV\VWHPUDLVHVWKH F[BV\BDULWKPHWLFBRYHUIORZ H[FHSWLRQ '$7$UHVXOW7<3(L WH[W7<3(VWULQJ UBH[F7<3(5()72F[BURRW 75< UHVXOW LQW LQW :5,7(UHVXOW &$7&+F[BV\BDULWKPHWLFBRYHUIORZ,172UBH[F WH[W UBH[F!JHWBWH[W 0(66$*(WH[W7<3( , (1'75< Information L 2YHUIORZLQWKHRSHUDWLRQ " SAP AG 2002 n In the above calculation, if the value range for data type i is exceeded, the runtime system raises the exception CX_SY_ARITHMETIC_OVERFLOW. This exception is handled in the implemented CATCH block. n The object reference to the exception object is stored in the reference variable r_exc. Using r_exc and the functional method get_text, the handler accesses the exception text for this exception object and stores in the string variable text. n To display exception texts as messages, the MESSAGE statement has been extended so that you can use any string: MESSAGE <string> TYPE <type>. As well as the message <string> that will be displayed, you must display the message type <type>, either as a literal or in a field. n If the value range for data type i is not exceeded, no exception is raised and the TRY block is processed completely. The program then continues executing after the keyword ENDTRY. n The class CX_SY_ARITHMETIC_OVERFLOW is a subclass of the classes CX_SY_ARITHMETIC_ERROR, CX_DYNAMIC_CHECK, and CX_ROOT. Thus the exception raised above can also be handled if you enter one of these classes after the CATCH statement. n The keyword documentation for each keyword lists the exception classes whose exceptions may occur when the appropriate ABAP statement is executed. © SAP AG BC401 14-7 ([DPSOH8VLQJ<RXU2ZQ([FHSWLRQV ¿UÀ£ÁÃÂ0ÂÅÄ·ÆUÄÇ È ÉÊË ÄÈ·ÌJÍ ÚJÓçJÎÔ Î¡Õ*ÎÖÔ × ×·×U× Ð ÓUÕ0Ù0Ö·Ú Â Û!U Í Ý½ÇÒÝ¡ÍUÆÞJÌÉÆ0ÈUÄ£Ç È*Ý0Ý·ÊUÉhßJà Ýͤá Î,ÐÒÑÖ0èJդνÔ*ãõɽó·ÇÒÝhñ0Ë*Í Õ Ñ Ó Ó¤ÑÖ0èJդνÔ*ãåÍ0ìhÇäUÍ*ÉÛ·Þ Ý Õ Ñ Ó Í0ìhÇÒÝÈ·Ì!æJÆ0ÈËõÕ Ñ Ó ×·×U× ÓJÔ·Ú¿0ÀhÁÂJÂÿ× áÈË ÄÈÌJÍ ö£Ë Ä·È·ÌJÍ*Ýhñ0Ë!Í á7ÇË ÄÈÌhÇäUÍ*É á7ÇÆ·ÈËUÈUÆUÉJÝWñØ× ¿UÀ£ÁÃÂ0ÂÅÄ·ÆUÄÇ È ÉÊË ÄÈ·ÌJÍÏÎ,ÐÒÑÀJÓhÐÓ·Ô*ÕWÁ¤Õ*ÎÖÔØ× ×·×U× Ð ÓUÕ0Ù0Ö·ÚÜ۷ͤÝÇÝÍ!Æ¡ÞUÌ*É·Æ·È*Ä7ÇÒÈUÝJÝÊ!ÉWßUàÝ¡Íá× ÂÓUÀ·ÓU¿JÕâ·ÎhÔ!ãJÀÓÅäUÍ*É¡ÛÞ}ÝåÝ¡È0ÌJæUÆ·ÈËÏç¡èUÖWÐéá¡È¡Ë¤Ä¡ÈJÌ0Í ÎWÔ!Õ0ÖëêjÍJì£Ç}ä0ÍÉÛ0ÞÝîíÍ0ìÇÒÝÈÌUæJÆ0È¡ËÒï ð Ù·ÓJè0ÓåˤÄÈUÌ·ÍÝWñJËUÍÅòâÉWóÇÃÝ£ñJËUÍô× Îçõá£ñöá¡à¡ß Ê0Æø÷ ùâúî× ÍJìWÇ ä0ͤÉWÛJÞÝûòÏüJú0úJú·ú!ú× ÍJìWÇÃÝÈUÌ·æ!Æ·ÈËÜòÏü0úJú·ú!ú× Ó0Ô0Ú}Ρçý× $GDSWLQJWKHSURJUDP ÓJÔ0ÚÐ*Ó!Õ·ÙJÖ¡Úþ× ,IWKHUHLVQRWDEOHHQWU\DYDLODEOH ×·×U× UDLVHDQGKDQGOHDQH[FHSWLRQ\RX ÓJÔ·Ú¿0ÀhÁÂJÂÿ× KDYHZULWWHQ SAP AG 2002 n The above program source code shows the method get_technical_attributes of the class lcl_airplane, which was implemented in an earlier exercise in this training course. It receives an airplane type as an import parameter and returns its weight and tank capacity as export parameters. n The relevant information is read from the database table VDSODQH. If the airplane type passed is not available in this table (that is, if sy-subrc <> 0), the values 100.000 and 10.000 respectively are assigned to the export parameters ex_weight and ex_tankcap. We will now change this behavior: If an airplane type is not entered in the table, an exception that we have defined should be raised and handled appropriately. © SAP AG BC401 14-8 &UHDWLQJ<RXU2ZQ([FHSWLRQ&ODVVHV Workbench Edit Goto MIME Repository Object Navigator Repository Infosystem Tag Library Transport Organizer Utilities Environment ,.-$/1032546232 /87 9;:;: <)= >5( 95( ? /@7 9A:A:3#;: Help "$#&%&')( * ! SULYDW =&;B:521*B3/$1(7<3( SURWHFWHG + &;B67$7,&6B&+(&. ,QKHULWV)URP DEVWUDFW &ODVV7\SH 8VXDO$%$3&ODVV ([FHSWLRQ&ODVV 3HUVLVWHQW&ODVV &ODVV B)9AC5DE9;F# ,G-$/H032&462A2 Object Name System Description ! )LQDO&ODVV 2QO\PRGHOHG SAP AG 2002 n Exceptions are represented by objects that are instances of exception classes. Defining an exception is thus synonymous with creating an exception class. n Exception classes are generally defined globally. For special exceptions that will only occur within a single ABAP program however, you can also define local exception classes. n Global exception classes are defined and managed in the Class Builder. When you create a new class, if you use the correct naming convention (prefix ZCX_) and choose the class type ([FHSWLRQ &ODVV, the system automatically displays the ([FHSWLRQ%XLOGHUinstead of the Class Builder. n The ([FHSWLRQ%XLOGHU offers all the functions you need to create exception classes and generates specified components that cannot be changed. When you create an exception class, you must also specify which category of exception it will be - that is, whether it is derived from CX_STATIC_CHECK, CX_DYNAMIC_CHECK or CX_NO_CHECK. © SAP AG BC401 14-9 0DLQWDLQLQJ<RXU2ZQ$WWULEXWHVDQG([FHSWLRQ 7H[WV Class Edit Goto Utilities Environment System Help IKJMLONPNRQTSUEJVXW!Y[Z\IK]XLO^`_aWbIKJMLONPNdceIgfihXjlknmpo qrhPsut\vwoyxiz\{\sux §¬ GG\°HH$²µH.} )}¶ ¡ §¬ G)¤)}¤­ 1) ® 8H¯ ° ± ¦£|!HH¥ ¡ <RXURZQDWWULEXWHV SURYLGHWKHXVHUZLWK | }~}M .} H81 DGGLWLRQDOLQIRUPDWLRQ @ [ ¡.)} ¦8 ~ ¤)1} H ¦8 $! O¡ ¤)1} H ¦8 ¢! ¡£ ! ¤ ¤)1} H ¦8 ¡£ H¥ ¤)1} H ¦8 | }~} H.}) ¸ ¸ ¸ ¸ ²\ ¬ $²PG} 11³ |)} ´$ 81} ·8 ¬ } H HH8 $ | ..8$ )}11@. ¦ H81 ¦ H81 § H81 ¡ ¦¨1©Gª ! H81 H81 |¦£ | [@«¦£G|!8.¥ ¦ ([FHSWLRQWH[W XVHGWRGHVFULEH H[FHSWLRQVLWXDWLRQ LQPRUHGHWDLO Exception ID Text CX_ROOT An exception occurred ZCX_WRONG_PLANETYPE This airplane type is unknown SAP AG 2002 n The methods are all inherited from CX_ROOT. You can also add your own methods. The instance constructor is generated automatically. n You can also define your own attributes, whose contents specify the exception in more detail. The ([FHSWLRQ%XLOGHU ensures that the instance constructor has identically-named IMPORTING parameters for these attributes. n The exception texts of global classes are defined on the 7H[WV tab of the Exception Builder. They can contain parameters. To do this, use the elementary attributes of the exception class by enclosing their name in ampersands (’&’) in the exception text. n The exception texts of global exception classes are stored in their different translations in the 2SHQ 7H[W5HSRVLWRU\ OTR). Note that several texts can be assigned to a single class. You assign a text to an exception using the TEXTID attribute, which contains the globally unique ID of the text object within an exception object at runtime. The method GET_TEXT then exports this text, replaces any text parameters with the contents of the relevant attributes as necessary, and returns the text as a character string. n For each global class, the Exception Builder generates a default text whose name matches the class name. (The name of this default text cannot be changed.) You need to create names for other texts. For each text, the Exception Builder generates a static constant that contains the associated ID in the OTR. You can then specify which text is to used when an exception is raised by passing an identifier to the IMPORTING parameter TEXTID of the instance constructor. If you do not specify a text, the default text is used. © SAP AG BC401 14-10 5DLVLQJDQG+DQGOLQJ([FHSWLRQV<RX+DYH:ULWWHQ Ð*Ó!Õ·ÙUÖÚÜÛJÍ*ÝÇÝ¡ÍUÆ·ÞJÌÉÆ0È!ÄǤÈ*Ý·ÝJÊJÉhßJà ÝÍ áî× Ú·Á ÕhÁº¹Ê£ÇÍJìUÆÅÕ Ñ ÓÅè0Ó*çÅÕÖÜÆ·ìWÇÊ»[»!Ýÿí Ý¡Í·ìÝ Õ Ñ Ó á·Ý·ÊJÉ·Ì·Ûô× ([DPSOH LPBW\SH $ ¡ÓUÀ·ÓU¿JÕõÂ0ÎWÔ!ãUÀÓÅäUÍ*É¡Û·Þ Ý ÝÈ0ÌJæUÆ·ÈËâç¡è!ÖhÐ á¡È¡Ë¤Ä¡È0Ì0Í ÎhÔ!Õ0ÖëêjÍJìWÇ ä0ͤÉhÛ0ÞÝîíÍ0ìhÇÒÝ·È·ÌUæ0Æ0È¡ËÒï ð Ù·ÓJè0ÓåˤġÈ0̷ͤݣñJËUÍÅòâÉ£óÇÝWñJËJÍô× Î·çõá£ñö·áhàßÊ0Æ Õ·è × ÷ ùâúî× Ó°!¿·ÓÑÕ*ÎÖ¡ÔâÕ ÑÓ½¼¡Æ·ìWǤä!Ê°»ÌJÛWÇË ÄÈ·ÌUÍ*Ýhñ0Ë!Í Ó¤ÑÖ0èUÕÎ½Ô ãûË ÄÇÒÝhñ0Ë!Í òâÉó·ÇÒÝhñ0Ë!Í × ¿hÁ ÕJ¿Ù¾¼·ÆìhÇä*Ê»0Ì0ÛhÇ!ËÄÈ0Ì0ÍÝWñJËUÍÏÎhÔ!Õ0Ö Ê½Ç¤Í0ì!Æ× Ý¡Í·ìÝ òÜʽǤÍ0ì!Æ*öùÛ!Í!ÝÇÒÝ¡Í0ìÝ ê ïî× ÐÓ*ÂJÂÁ}ãÓÏÝ¡Í0ìÝ Õ ÑWÓÀ¿2Îg¿0× Ó0Ô0Ú*Õè × è¡ÁÎ0ÂhÓ ÓJÔ0Ú}Ρçý× Information L Ó·ÔJÚ¡Ð ÓUÕ0Ù0Ö·Ú × 7KHDLUSODQHW\SH$LV XQNQRZQ " SAP AG 2002 n If the airplane type passed to the method has not been stored in the table VDSODQH, the exception we defined previously, ]F[BZURQJBSODQHW\SH, is raised. In addition, a TRY-ENTRY control structure is implemented that is only processed if sy-subrc <> 0. n The TRY block contains the application code that is to handle the exceptions. When the exception is raised, the IMPORTING parameter SOBW\SH of the instance constructor is filled. (This parameter is automatically generated by the Exception Builder.) Using this parameter, the program then assigns the value of the airplane type to the identically-named attribute. n The exception that has been raised is handled in the CATCH block. The reference to the exception object is stored in the reference variable UBH[F, which was created as a local data object in the method (TYPE REF TO cx_root). n Since the IMPORTING parameter TEXTID of the instance constructor was not filled when the exception was raised, the default text generated when the exception class was created is addressed using the functional method JHWBWH[W. The method GET_TEXT then exports this text, replaces the text parameter with the contents of the attribute SOBW\SH, and returns the text as a character string. n The returned text is stored in the local data object WH[W, which has the type VWULQJ The text is then displayed as an information (type ,) message. © SAP AG BC401 14-11 3DVVLQJ([FHSWLRQV$ORQJ ¿JÀ£ÁÒÂ0 Æ*ÄÈ 0 á á ÚUÓUç*ΣÔ}ÎÕ ÎhÖ·Ô × ×·×J× Ð!Ó!Õ·ÙJÖÚ} ó* Í ÝhÞÏÎÐÑÖè*Õ*ÎWÔ!ã ÷ Éó·Ç*ËÈJÊ0ÈhóÍ*Ý¡ÍUÊ0ù Ó° ÑÖè*Õ*ÎWÔ!ã ÷ Í·ìhÇ*ËÈJÊ0ÈhóÍ*Ý¡ÍUÊ0ù è¡ÁÒÎJÂ0ÎhÔ!ã Æ ì£Ç¤Í0ì*ÆÍ·Ë ÝJÉ¡»0Ì × · ×·×J× Ó0Ô·Ú*¿0ÀhÁÂUÂî× èUÓÑ¡Ö·è!Õ Ë*Ê°»Ë È ÛUÈ!Ý¡ÍWǤÍ0ì!ÆÍ0Ë ÝJÉ@»0Ìáÿ× ×U×0× Ú·Á ÕhÁ ʽǻ¡ßÁ Õ ÑhÓÅèJÓ!çåÕJÖÜÆJÄÈ*áJáî× ×U×0× Õ0è × Ê½Ç»¡ßÁJöùWó¤Í!ÝÞþê Ó° Ñ¡Ö·è*Õ*ÎWÔUã ÎÐÑ¡Ö·è*Õ*ÎWÔUã ¿UÀWÁÒÂ0 Æ!Ä¡È áá ÎÐÑÀÓ¡Ð*Ó0Ô!ÕÁ ÕÎWÖ·Ô × ×0×J× Ð*Ó!Õ·ÙJÖÚ ó ÍUÝÞ × ×J×0× è¡ÁÒÎ0ÂhÓÅÓ°U¿JÓ*ÑÕ*ÎÖÔõÕ Ñ¡ÓõÆ¡ìhÇ ÍJU ì Æ·ÍË}Ý0ɦ»·Ì × Ó·ÔJÚ¡ÐÓUÕ0Ù0Ö0Ú × ÓJÔ0Ú*¿0ÀhÁÂJÂÿ× Â ×J×0× ×J×0× ïî× ¿hÁ ÕJ¿·ÙÜÆ·ì£ÇÍ·ì!ÆÍ·Ë ÝJÉ¡»0Ì × ×J×0× Ã ¬·»«0¾¡ª ­ ¹*±¡¸ ªAÄ¡Å¡ª!¹J»»0ºJ° ­± ¾J°c¹J»h«¡® ºJ°¢«¡¸þ®J¹ ±¹·ª ±·«¡»h«h¸¸¡Å0°­² Æ ±¡«¡«® ªj¹wÇ¡«uĦÅJ±®² «¡®þª3Ä¡«J°¢« Èhª;Ä¡«Æ »8ÅU±eÇ¡« ¾¡Åh¸¡¸«¡®ÉÅ0² ¹*± ¶ ªj¹ ª;Ä« »8ÅU²²­± ¶ ¾J°¼¹ ¶ °Å¦Ê ´ ó ÓJÔ0Ú*Õè × SAP AG 2002 n Exceptions that occur in procedures (methods, function modules, or subroutines) do not necessarily need to be handled there; they can be passed along to the calling program. The calling program can then handle the exception itself or also pass it along to its own caller, and so on. n The highest levels to which an exception can be passed are processing blocks without local data areas - that is, event blocks or dialog modules. The exceptions passed along by the called procedures must be dealt with there, as must any exceptions raised within this processing block itself. Otherwise a runtime error occurs. n To pass along an exception from a procedure, you generally use the RAISING addition when defining the procedure interface. n In methods of local classes and subroutines, specify the RAISING addition directly when defining the procedure (METHODS meth ... RAISING cx_... cx_..., FORM form ... RAISING cx_... cx_...). After RAISING, list the exception classes whose objects are to passed along. n In methods of global classes, the exception classes whose objects are to be propagated are entered in the exception table of the method in the Class Builder. Check the ([FHSWLRQ&ODVV field in this exception table. Similarly, exceptions raised by function modules are passed along by being entered in the Function Builder. © SAP AG BC401 14-12 ([DPSOH3DVVLQJ([FHSWLRQV$ORQJ ¿JÀ£Á·ÂÅÄ·ÆUÄǤÈ*ÉÊË ÄÈÌJÍ ÚJÓ*ç!ÎhԤΡÕ*ÎÖ¡Ô × ÐÓUÕ0Ù0Ö·Ú ÂÌË ÉJáWËÄÈ¡ñ¡Ç¤È*Ý0Ý0ÊJÉßJà ÝhÍ áî× ÐÓUÕ0Ù0Ö·Ú ÂûÛUÍ*ÝÇÝ¡ÍUÆÞJÌÉÆJÈUĽǤÈ*Ý·Ý·ÊUÉhßJà¤Ýhͤá ÎÐÑ¡Ö·è*Õ!ÎhÔ!ãõÉ£ó¡ÇÃÝWñJËUÍ Õ ÑhÓ á¡È¡Ë¤Ä¡È0Ì0ͤöËÄÈ0Ì0ÍÝWñJËUÍ Ó° Ñ¡Ö·è!Õ*ÎhÔ!ãåÍJì£Ç äJÍÉÛJÞÝ Õ ÑhÓ á,Ç*ˤġÈ0ÌWÇ ä0Í¤É ÍJì£ÇÃÝ¡È0ÌJæ!Æ·ÈË Õ ÑhÓ á,Ç}Æ0È¡Ë*ÈJÆ!É·Ý¡ñ è¡ÁÒÎ0ÂJÎWÔ!㠼ơìhÇä*Ê»JÌ0ÛhÇ*ˤġÈ0Ì·ÍÝWñUËUÍ × Ó0Ô·Ú ¿·ÀhÁÂJÂÿ× ÐÓUÕ0Ù·Ö·ÚÍË*ÉUá£Ë¤Ä¡ÈñÇ}ÈUÝ!Ý¡Ê!ÉWßUàÝ¡Íáÿ× Ú¡Á¤Õ£Áu¹ ʽǤÍ0ì!ÆåÕ ÑWÓ èJÓ!çåÕ0ÖÜÆìÇ}Ê°»»*Ýí ÝÍJì*Ý Õ ÑWÓ á0ÝÊ!ÉÌJÛ × ×0×J× Õè × Û·ÍÝ,ÇÝÍ!Æ¡ÞUÌ*É·Æ·È*Ä7ÇÒÈUÝJÝÊ!ÉWßUàÝ¡Íáôê Ó° Ñ¡Ö·è!Õ*ÎWÔUãâÉ£óÇÃÝWñJËUÍÅòåˤÄÈ0Ì0ÍÝWñJËUÍ ÎÐÑ¡Ö·è!Õ*ÎWÔUãÅÍJìWÇ äJÍÉÛ0ÞÝ ò äUÍ*É¡Û·Þ Ý ÍJìWÇÃÝ¡È0ÌJæUÆ·È·ËÜò Æ·ÈË ïÃ× ð è¤ÎÕ0ÓιdÏ¿@ã0Í·ä É¡Æ0Þ*ݹ[¿*êúJúÐ*ïí ä*Í!É¡Û·Þ Ýí ¿@ÕJÈ·ÌUæ·æ!ÈË*ȼ0É0ݦÑ!ݹ[¿ê ú!úÒ!ïí Æ0È¡ËØ× ¿hÁÕJ¿·Ù½¼ÆìhÇä*Ê»0Ì·Û¡Ç!ˤġÈ0Ì0ÍÝWñJËUÍ ÎWÔUÕ0ÖÜʽǤÍ0ì*Æ × ÝhÍJì*Ý òÜ棂 ÍJìUÆöWùUÛ·ÍÝ,ÇÃÝÍJì*Ýôê ï× Ð!Ó Â0£Á ã·ÓÏÝÍJì*ÝûÕ ÑÓÀ¿Î¿·× Ó·ÔJÚUÕ·è × Ó0Ô0ÚÐ!Ó!Õ·ÙUÖÚ × ÐÓUÕ0Ù0Ö0ÚÜÛ·ÍÝ,ÇÃÝÍ!Æ¡Þ!Ì*É·Æ·È*Ä7Ç}È!ÝJÝÊ*ÉWßUàÝ¡Íáÿ× ÂhÓ!ÀÓ*¿0ÕÜÂUΣÔ*ã0À·Ó äJÍÉÛ0Þ*ÝÅÝÈ·Ì!æJÆ0È¡Ë çè0ÖÐéáÈË Ä·È·ÌJÍ ÎWÔUÕ0ÖëêjÍJìWǤäJÍÉÛ0Þ*ÝîíÍ0ìÇÒÝÈ·ÌUæJÆ0ÈËÒï ð ÙÓJè0ÓåˤġÈJÌ0ÍÝWñJËJÍÅòâÉWóÇÃÝWñJËUÍô× Î¡çõáhñ}ö0á£à0ß*ÊJÆø÷ùÏúÿ× ó è¡ÁÒÎJÂhÓåÓ°!¿·ÓÑÕ*ΡÖÔ Õ ÑÓ½¼¡Æ·ìWǤä!Ê°»·ÌJÛ£ÇË ÄÈ·ÌUÍ*Ýhñ0Ë!Í Ó°Ñ¡Ö·è!Õ*ÎWÔ!ã ˤÄ,ÇÃÝ£ñJËUÍÅòÏÉ£óÇÃÝWñJËJÍ × Ó·ÔJڤηç× Ó0Ô0ÚÐ*Ó*Õ·ÙJÖ¡Ú × SAP AG 2002 n As in the previous example, the exception we have defined (]F[BZURQJBSODQHW\SH) is raised if the airplane type passed to the method JHWBWHFKQLFDOBDWWULEXWHV is not stored in the table VDSODQH. Here, however, the exception is only raised in the method JHWBWHFKQLFDOBDWWULEXWHV, not handled there. n To pass the exception along to the caller of the method, we enter it after the RAISING keyword. n Now, the caller - that is, the method GLVSOD\BDWWULEXWHV- handles the exception. For this purpose, we have implemented a TRY-ENDTRY control structure in this method. The method JHWBWHFKQLFDOBDWWULEXWHV is now called in the TRY block of this control structure. n If the exception is raised in the method JHWBWHFKQLFDOBDWWULEXWHV, the program continues by handling this exception. That is, the method JHWBWHFKQLFDOBDWWULEXWHV is terminated and the appropriate CATCH block is processed within the caller. Note in particular that the program no longer executes the WRITE statements entered in the TRY block DIWHU JHWBWHFKQLFDOBDWWULEXWHV is called. © SAP AG BC401 14-13 ([FHSWLRQV7KDW0XVW%H'HFODUHG F[BURRW F[BQRBFKHFN   ¹ ºØ»@Å0±ÉĦÅ0±®² «ØªEÄ¡«¡¸¡« Ó * «h¬·»h«J¾¡ª@­ ¹*±¸ Æ·¹*ºØ®U¹ ±¹JªÖ ´@Ô Õ ª3Ä¡«ÆKÅU°¢«¦¾¦Åh¸¸·«¡®uÅ0²¹*± ¶ ÅJºª¼¹!ÊaŪc­ »@Å0²² Æ ´ Ó ¹*º »8ÅJ±U±¹·ª ¾¦Åh¸¸þª;Ä¡«¦Êû«h¬!¾J²­ »·­ ª9² Æ º¸U­± ¶ ª3Ä¡«a×§Ø Ô ÙÔÚÜÛ Å®J®*­ ª ­ ¹*± ¯ Ú ¹·ª ¾¦Å0°¢ª!¹ Õ ¸8Æ*±ªÅh¬ »Ä¡«»   F[BG\QDPLFBFKHFN ¹ ººÊ º¸ª§Ä¦ÅJ±®*² «ôªAÄ«¸¡« Ó * «h¬0»h«0¾ª9­ ¹*±¸ ¹*° ¾¡Å¸¡¸Øª;Ä¡«¦Ê ÅJ² ¹*± ¶ «h¬!¾J²­ »0­ ª ² Æ º¡¸J­± ¶ ªAÄ¡« ×§Ø Ô ÙÔÚÜÛ Å®J®*­ ª ­ ¹*± F[BVWDWLFBFKHFN ¯ Ú ¹·ª ¾¡ÅU°¢ª!¹ Õ ¸8ÆU±ª¶Åh¬ »°Ä¡«¡»   ¹ ººÊ º¡¸¡ª§Ä¦Å0±®*² « Ó ªAÄ¡«¸¡« «W¬0»h«J¾¡ª@­ ¹*±¸ ¹*° ¾¡Åh¸¡¸Øª;Ä¡«ÊÝÅ0² ¹*± ¶ «W¬U¾U²­ »·­ ª ² Ʀº¸!­± ¶ ª3Ä¡« × Ø Ô ÙÔÚ§Û Å®J®*­ ªc­¹*± Þ ÅJ°¢ª!¹ Õ ¸8Æ!±¡ª¶ÅW¬ »[Ä¡«¡» ¯ SAP AG 2002 n Subclasses of CX_STATIC_CHECK: The relevant exception must either be handled, or passed along explicitly using the RAISING addition. The syntax check ensures that this is the case. At present, only exceptions you define yourself for error situations in the application code are subclasses of CX_STATIC_CHECK. n Subclasses of CX_DYNAMIC_CHECK: The relevant exception does not have to be declared. If such an exception occurs at runtime, just as with subclasses of CX_STATIC_CHECK, it must either be handled or passed along explicitly using a RAISING addition. However, this is not checked in the syntax check. If such an exception occurs at runtime and is not either handled or passed along, a runtime error occurs. Most predefined exceptions with the prefix CX_SY_... for error situations in the runtime environment are subclasses of CX_DYNAMIC_CHECK. n Subclasses of CX_NO_CHECK: These exceptions cannot be declared. These exceptions can be handled. Otherwise they are automatically passed along. The syntax check never finds an error here. All exceptions of the category CX_NO_CHECK that are not handled in the call hierarchy are automatically passed to the top level, If they are not caught there, they cause a runtime error. Some predefined exceptions with the prefix CX_SY_... for error situations in the runtime environment are subclasses of CX_NO_CHECK. © SAP AG BC401 14-14 ([FHSWLRQ+DQGOLQJ8QLW6XPPDU\ <RXDUHQRZDEOHWR l &UHDWH\RXURZQH[FHSWLRQFODVVHV l 5DLVHH[FHSWLRQVLQDSURJUDP l +DQGOHH[FHSWLRQV l 3DVVH[FHSWLRQVDORQJ SAP AG 2002 © SAP AG BC401 14-15 ([HUFLVH 8QLW ([FHSWLRQ+DQGOLQJ 7RSLF 'HILQLQJUDLVLQJSURSDJDWLQJDQG FDWFKLQJFODVVEDVHGH[FHSWLRQV At the conclusion of these exercises, you will be able to: • Define exception classes • Raise class-based exceptions • Pass exceptions along • Catch class-based exceptions Improve your program so that, when the airplane attributes are displayed, an error text is displayed instead of the default values if the airplane type is invalid. Implement this using the class-based exceptions concept. 3URJUDP 7HPSODWH =%&BB5$,6(B75< 6$3%&B(9(6B0$,1B% 0RGHOVROXWLRQ 6$3%&B(;&6B5$,6(B75< LV\RXUWZRGLJLWJURXSQXPEHU 1-1 1-2 Copy your solution to the last exercise from the unit (YHQWV, or the corresponding model solution 6$3%&B(9(6B0$,1B%, with all their includes. Give them the new names =%&BB5$,6(B75<, =%&BB5$,6(B75<B&/, and =%&BB5$,6(B75<B&/. Define a JOREDO exception class. (We suggest the name =&;BB,19$/,'B3/$1(7<3(.) Choose the appropriate superclass so that the system performs a syntax check to ensure that, after the relevant exception is raised, it is either handled or passed explicitly along using a RAISING addition. Add an attribute for the airplane type (suggested name: 3/$1(7<3() and assign the type 6B3/$1(7<3( to it. Create a default error message that can be enhanced dynamically to include the airplane type. 1-3 © SAP AG Raise the exception in the JHWBWHFKQLFDOBDWWULEXWHV method of your local class OFOBDLUSODQH. Add a 5$,6,1* addition to the definition part of the method, so that the exception can be passed along. BC401 14-16 1-4 © SAP AG Catch the exception in the GLVSOD\BDWWULEXWHV method of your local class OFOBDLUSODQH. To do this, you will need a local reference to the exception instance (suggested name: UBH[FHSWLRQ). Assign a type to this reference using the superclass &;B5227. Read the error text from the exception instance using the JHWBWH[W method. To do this you will need an auxiliary variable of the type VWULQJ (suggested name H[FBWH[W). BC401 14-17 6ROXWLRQ 8QLW ([FHSWLRQ+DQGOLQJ 7RSLF'HILQLQJSURSDJDWLQJDQGUDLVLQJHYHQWV 0RGHOVROXWLRQ,QFOXGH%&B(;&6B5$,6(B75<B&/ *&---------------------------------------------------------------------* *& Include BC401_EXCS_RAISE_TRY_CL2 * *&---------------------------------------------------------------------* ... *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION * *------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes. EVENTS: airplane_created. PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type TYPE saplane-planetype EXPORTING ex_weight TYPE s_plan_wei ex_tankcap RAISING DATA: name TYPE s_capacity cx_bc401_invalid_planetype. TYPE string, planetype TYPE saplane-planetype. © SAP AG BC401 14-18 CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS. "lcl_airplane DEFINITION *------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. ... ENDMETHOD. "constructor METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap, r_exception TYPE REF TO cx_root, exc_text TYPE string. WRITE: / icon_ws_plane AS ICON, / ’Name des Flugzeugs’(001), AT pos_1 name, / ’Type of airplane: ’(002), AT pos_1 planetype. * handle exception in case of invalid planetype: 75< get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ). WRITE: / ’Gewicht:’(003), weight, ’Tankkap:’(004), cap. &$7&+F[BEFBLQYDOLGBSODQHW\SH,172UBH[FHSWLRQ H[FBWH[W UBH[FHSWLRQ!JHWBWH[W :5,7(H[FBWH[W&2/25&2/B1(*$7,9( (1'75< ENDMETHOD. "display_attributes METHOD display_n_o_airplanes. ... ENDMETHOD. "display_n_o_airplanes METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) © SAP AG BC401 14-19 WHERE planetype = im_type. IF sy-subrc <> 0. 5$,6((;&(37,217<3(F[BEFBLQYDOLGBSODQHW\SH (;3257,1*SODQHW\SH LPBW\SH ENDIF. ENDMETHOD. ENDCLASS. © SAP AG "get_technical_attributes "lcl_airplane IMPLEMENTATION BC401 14-20 '\QDPLF3URJUDPPLQJ &RQWHQWV l '\QDPLFDWWULEXWHV l 'DWDUHIHUHQFHYDULDEOHV l )LHOGV\PEROV l 5XQWLPH7\SH,GHQWLILFDWLRQ 577, SAP AG 2002 © SAP AG BC401 15-1 '\QDPLF3URJUDPPLQJ8QLW2EMHFWLYHV $WWKHFRQFOXVLRQRIWKLVXQLW\RXZLOOEHDEOHWR l 8VHG\QDPLFDWWULEXWHVLQVXLWDEOH$%$3 VWDWHPHQWV l 8VHGDWDREMHFWVJHQHUDWHGDWUXQWLPH l $VFHUWDLQWKHDWWULEXWHVRIGDWDREMHFWVDWUXQWLPH SAP AG 2002 © SAP AG BC401 15-2 '\QDPLF3URJUDPPLQJ ,QWHJUDWLRQLQ&RXUVH&RQWHQW }~0 u| _ b ` j ] d ^ r o ^ m a ] ^ n E A = A CF@G > 7 A 7 3: 9 H: E A = AJI DLK >M = E > =A 9B x ` b _ ] oay b _ r ^ ] z{ b c q ^ j b \ e o _@b c w a d g oa t a o c c b c o ^ m u8v b ^ j c q^ jb \ eo _ b c t o c j]^ n q ^2r b \s] j o ^ _ b ]^ \] b ^ j bkm [ \ d3n \ op p n [,\ ] ^_ ] `a b cJd2e2fXgih b _kj l f " " ! 687 9 :;!< := >@? : AB C A D B> 7 #$% % & '(*),+- ( + $.0$5 / $ $ '21!) $ / / & '3(*4 NPO8Q R STVUXW T R W@Y T@Z SAP AG 2002 © SAP AG BC401 15-3 '\QDPLF3URJUDPPLQJ )LHOG6\PEROVLQ'HWDLO )LHOG6\PEROVLQ'HWDLO '\QDPLF&DOOV '\QDPLF&DOOV 'DWD5HIHUHQFHV 'DWD5HIHUHQFHV $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ SAP AG 2002 © SAP AG BC401 15-4 )LHOG6\PEROV ),(/'6<0%2/6IV!7<3(_/,.(_7<3($1<` $66,*1GDWDREMHFW72IV! 81$66,*1IV! IV!,6$66,*1(' '$7$LQW7<3(L9$/8( ),(/'6<0%2/6IVBLQW!7<3(L *HQHULFRU FRPSOHWHW\SH VSHFLILFDWLRQ * 2 s $66,*1LQW72IVBLQW! :5,7(LQWIVBLQW! * 2 s IVBLQW! :5,7(LQWIVBLQW! * 2 s * 2 s 81$66,*1IVBLQW! ,)IVBLQW!,6$66,*1(' :5,7(LQWIVBLQW! (/6( :5,7( ILHOGV\PEROQRWDVVLJQHG (1',) IQD SAP AG 2002 n You declare field symbols using the ),(/'6<0%2/6IV! statement. Note that the parentheses (<>) DUH part of the syntax. n Field symbols allow you to access an assigned data object - that is, all the accesses that you make to the field symbol are made to the data object assigned to it. Field symbols are similar to dereferenced pointers. Thus, you can only access the content of the data object to which the field symbol points. (That is, field symbols use value semantics). n You use the ASSIGN statement to assign a data object to the field symbol IV!. If the field symbol is generically typed (TYPE ANY), it adopts the type of the data object. By specifying a type for the field symbol, you can ensure that only compatible objects are assigned to it. Example: DATA: date TYPE d VALUE ’19991231’, time TYPE t. FIELD-SYMBOLS: <fs_date> TYPE d, <fs_time> TYPE t. ASSIGN: date TO <fs_date>, time TO <fs_time>. <fs_time> = <fs_date>. returns a syntax error. Conversely, using the following construction would deliver a runtime error:FIELD-SYMBOLS: <fs_date> TYPE ANY, <fs_time> TYPE ANY. n Use the expression <fs>IS ASSIGNED to find out whether the field symbol <fs> is assigned to a field. n The statement UNASSIGN <fs>. sets the field symbol <fs> so that it points to nothing. The logical expression <fs> IS ASSIGNED is then false. © SAP AG BC401 15-5 7KH&$67,1*$GGLWLRQ $66,*1GDWDREMHFW72IV!&$67,1*>7<3(W\SH_@ ,QKDOWGHV]XJHZLHVHQHQ 7KHFRQWHQWRIWKHDVVLJQHG 'DWHQREMHNWVZLUGVR GDWDREMHFWLVLQWHUSUHWHGDV LQWHUSUHWLHUWDOVREHUGHQ LILWKDGWKHLPSOLFLWRU LPSOL]LWE]ZH[SOL]LW H[SOLFLWW\SHVSHFLILHG DQJHJHEHQ7\SKlWWH 7<3(6%(*,12)VWBGDWH \HDU 7<3(Q PRQWK 7<3(Q GD\ 7<3(Q (1'2)VWBGDWH RSWLRQLPSOLFLW ),(/'6<0%2/6IV!7<3(VWBGDWH $66,*1V\GDWXP72IV!&$67,1* DFFHVVDIWHUFDVWLQJ :5,7(IV!\HDUIV!PRQWKIV!GD\ RSWLRQH[SOLFLW ),(/'6<0%2/6IV!7<3($1< $66,*1V\GDWXP72IV!&$67,1*7<3(VWBGDWH 0 ¢¡ s ,8X28 s s SAP AG 2002 n If you use the CASTING addition when you assign a data object to a field symbol that has a different type, you can remove the restrictions of having to use the data object’s original type. The access is then interpreted as though the data object had the data type of the field symbol. n If you use the CASTING TYPE <type> addition when you assign a data object to a field symbol that has a different type, you can access the data object using the field symbol as if the object had the type <type>. n In the above example, note that the system field sy-datum is an elementary character-type component of length . n You can also use type casting dynamically when you assign a data object to a field symbol. For example: PARAMETERS tabname TYPE dd02l-tabname. DATA: dummy TYPE i, line(65535) TYPE c. FIELD-SYMBOLS <fs_wa> TYPE ANY. ASSIGN line TO <fs_wa> CASTING TYPE (tabname). You can now access line through <fs_wa> as if this elementary data object had the same type as the line type of the transparent table passed using tabname. (You define the dummy data object only to ensure that line has the correct alignment). © SAP AG BC401 15-6 '\QDPLF3URJUDPPLQJ )LHOG6\PEROVLQ'HWDLO )LHOG6\PEROVLQ'HWDLO '\QDPLF&DOOV '\QDPLF&DOOV 'DWD5HIHUHQFHV 'DWD5HIHUHQFHV $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ SAP AG 2002 © SAP AG BC401 15-7 8VLQJ'\QDPLF$WWULEXWHVLQ6WDWHPHQWV l 5HSODFLQJDOLWHUDOZLWKDYDULDEOH l 5HSODFLQJDQLGHQWLILHUZLWKDYDULDEOHLQSDUHQWKHVHV £¥¤L¦§©¨ª«¦ VSDFHV &$//75$16$&7,21 7B&2'( G\QDPLF GDWDBREMHFW 7B&2'( &$//75$16$&7,21GDWDBREMHFW 68%0,7UHSRUWBQDPH G\QDPLF GDWDBREMHFW 5(3257B1$0( 68%0,7 GDWDBREMHFW l 5HSODFLQJDOLVWZLWKDQLQWHUQDOWDEOH 6(73)67$786 67$786B1$0( (;&/8',1* )& )& G\QDPLF ILOOLQWHUQDOBWDEOHZLWKIXQFWLRQFRGHV 6(73)67$786 67$786B1$0( (;&/8',1*LQWHUQDOBWDEOH SAP AG 2002 n In many ABAP statements, you can pass attributes dynamically. The syntax for doing this differs, depending on the statement you use: n If you pass the attribute as a literal in the static form of the statement, you can replace the literal with a variable. If you pass the attribute as an identifier in the static form of the statement, you can replace the identifier with a variable in parentheses. Make sure there are no spaces between either parenthesis and the variable. If the attribute is a list, you can replace it with an internal table. n Note: you PXVWuse upper case when filling data objects with literals. n For more information on which of these three options you can use with a specific ABAP statement if any - refer to the ABAP documentation for that statement. n In Open SQL statements, you can also specify the logical conditions of the WHERE clause dynamically at runtime, by entering the ABAP source code in a variable. In the FROM clause of the SELECT statement, you can specify either individual table names or a dynamic JOIN expression using a variable. Similarly, you can program the GROUP-BY and HAVING clauses in SELECT statements. For more information, refer to the keyword documentation. © SAP AG BC401 15-8 &DOOLQJ0HWKRGV'\QDPLFDOO\ ,QWHUQDO WDEOHW\SHV 7<3(322/DEDS 7<3(6DEDSBSDUPELQGBWDE 7<3(6DEDSBH[FSELQGBWDE µ¶·s¶¸ ¶X¹º¶¼»s½¼»¯¾¶ ¿ ºP»À ¿Á2ÂV¿ ¸ ¿Ã ¶»¶¸ Ï ¿Xà ¶Ð½··s½¸ ÃÑ¿Á Â!¿ ¸ ¿Ã ¶»s¶¸ ĽÆÅ Ç ¿ ¸ÉÈ ¿ÊÁ ¶ È Ë ÂV¿ ËË¶Ì Í½  » È ½X¹ ¿Á Î 7<3(322/6DEDS '$7$SWDE7<3(DEDSBSDUPELQGBWDE HWDE7<3(DEDSBH[FSELQGBWDE GDWDBREMHFW 0(7+2'B1$0( )LOOSWDEDQGHWDE &$//0(7+2'UHI! GDWDBREMHFW 3$5$0(7(57$%/(SWDE (;&(37,217$%/(HWDE ³ J´ ¬ ¡®­ ¯ Ï ¿ Ã Ñ ¶ ½· ¶PÒºP¶  » È ½X¹ ¡ J´ ° J±s² ¡ Ó ¿XÁ À¶¼·s½¸ Ë,ÔÕLËÀ Ê ¸º ¬ ¡ ° J±s² ¡ SAP AG 2002 n You can call instance and static methods dynamically using parentheses in the syntax, as is normal in ABAP. Use the PARAMETER-TABLE and EXCEPTION-TABLE additions of the CALL METHOD statement to pass the actual parameters dynamically. n The parameter table must have the attributes of the ABAP_PARMBIND_TAB table type. The table has three columns: NAME (for the name of the formal parameter); KIND for the way the parameter is passed (exporting, importing, changing, or receiving); VALUE with the type REF TO data (for the value of the actual parameter). n The way the parameter is passed is specified for each formal parameter in the declaration of the called method. Thus, the content of the KIND column can be initial. n For the value of the actual parameter, the VALUE reference of the line in the table must point to the data object containing that value. You can use the GET REFERENCE statement to achieve this. n The exception table must have the attributes of the ABAP_EXCPBIND_TAB table type. This table has two columns: NAME for the name of the exception; VALUE for the value to be assigned to sysubrc. VALUE must be of type i. © SAP AG BC401 15-9 '\QDPLF3URJUDPPLQJ )LHOG6\PEROVLQ'HWDLO )LHOG6\PEROVLQ'HWDLO '\QDPLF&DOOV '\QDPLF&DOOV 'DWD5HIHUHQFHV 'DWD5HIHUHQFHV $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ SAP AG 2002 © SAP AG BC401 15-10 'DWD5HIHUHQFH9DULDEOHV 7<3(6UHIW\SH^7<3(5()72W\SHBQDPH_ /,.(5()72GRBQDPH_ 7<3(5()72GDWD` $Q\FRPSOHWHO\ VSHFLILHGW\SH '$7$UHI^7<3(5()72W\SHBQDPH_ /,.(5()72GRBQDPH_ 7<3(5()72GDWD` *HQHULFW\SH DVVLJQPHQW *(75()(5(1&(2)GDWDREMHFW,172UHI × ¡ '$7$UHI7<3(5()72L GR7<3(L9$/8( JÖ *(75()(5(1&(2)GR,172UHI 2 × ¡ JÖ 2 *HWDUHIHUHQFHWRDGDWD REMHFW SAP AG 2002 n Data reference variables contain data references - that is, pointers to data objects. You use the TYPES reftype TYPE REF TO type_name statement to define a reference type to a data object, where type_name is any completely specified type. You can also use the generic variant TYPE REF TO data here. You define the data reference variable itself using the DATA statement. This reference variable is a data object that can contain any data object (TYPE REF TO data) or a data object of the specified type. n You work with data references using references. That is, when you access a data reference variable the data reference itself is accessed, so that changes are made to the addresses. n Data references are handled in ABAP like any data object with an elementary data type. This means that a reference variable can be defined not only as a single field, but also as the smallest indivisible unit in a complex data object, such as a structure or an internal table. n After it has been defined, the data reference variable is initial - that is, it contains an empty pointer. For a data reference variable to contain a reference that points to a data object, you must use this variable to get a reference to a data object that has already been declared (GET REFERENCE OF dataobject INTO ref). You can also assign an existing data reference from another data reference variable or generate a data object dynamically using it. (This will be discussed in more detail later.) © SAP AG BC401 15-11 ([DPSOH8VLQJ'DWD5HIHUHQFH9DULDEOHVLQ '\QDPLF0HWKRG&DOOV VÞXç©ß0ß !í"*ýÆþð!ý æVÛVû÷Pù÷Øã÷ÝÆù¼å å0åJå ãÛVØ 0ÝÆæãß ý*êíVïà 0ý Û ÚÝ !Ø*÷Xù ý*Xí!ïãàÆýúØJÙ*ÚÛ å0åJå ÿÆêÆîVðñ å ÛJù0æ"0Þç«ßJßå Ø0Ù*ÚÛÜ0ÚÝJÝJÞ*ßáàâãàäÑå æçØçÑèéäëêàâ ØJÙ*ÚÛìàâ*àäí*äãàJîïVâëðñJòXíêà0âôó õ àíãäãêàâöÞ÷XøJÛìÞ*÷Xù0ÛúÝ*ûáäêàâüó ïãý*êþ ØJÙ*ÚÛ ÿÆêÆîJðñ ó îÆ ý ØJÙ*Ú Û 0Û*û ØÝúòVà!êà ó òXí!ï*à ÆýúØJÙ*ÚÛ ÿÆêÆîJðñ å åJå0å 92:<;>=@?6;BA"=C D EFGIHKJ8GL=;KA"MCNJOFPQPBR ¬ ¡ ÛJØ JÛ!ûÛ J ÛÆù ÛìÝ!û òíJïà Jý ÷ ù*ØÆÝìîÆýüå àJýìîÆýôå õ àPíäêàâ«Ü* çëøÛÆå õ àPíäêàâ«ÜñVàïãý Û íÆ ÷ùãßÛ ! Ø õ àXí*äêàÆâ ÷ù*ØÆÝ Øç* ÞÛ ë ä êàâ¼å ïý!êþ ÛVØXíVç*øJÛ0å çãÞV Þ *Û! Ø JÝæ îXí©êÆî "! Ü$#%ïý*êþ'& Ú,ç ç *Û!Ø Û ëÜØXç JÞJÛ VÞPçßÆß !í"!ýÆþëð!ý ÷ «ÚÞÛ*Û0ù!ØçãØã÷ÝÆù¼å åå!å ëÛJØ 0ÝÆæ ýê8í*ïãàýüå ý *Xí!ïãà Æ ý ïà 0ý å ÛVùÆ æ *Û!Ø JÝæÑå åå!å ÛJù+ æ ÆÞç«ßJß å ³ 0´ ­ ° 0±¯² ¡ , - .0/21 , 3 ¬¥ ­ ¡ 46587465 äêàâ å ()ã÷ØÛ òí!ïãàý¼å SAP AG 2002 n In this example, the get_make method of the lcl_vehicle class is called dynamically. It has only one export parameter and no exceptions. n First we define a parameter table ptab with the global table type abap_parmbind_tab from the type group abap. The associated work area is called wa_ptab n We fill the work area wa_ptab with the associated values. We assign the name of the export parameter EX_MAKE to the component name. The component value contains the reference to the corresponding actual parameter gd_make. We also define the data reference variable ref (TYPE REF TO data) and fill the corresponding reference using GET REFERENCE. The kind component of the work area need not be filled. n We then insert this work area in the parameter table ptab using the INSERT statement. Finally we assign the name of the calling method to the data object meth. We then call the method using the syntax already shown. n After the method call, the actual parameter gd_make contains the passed value. © SAP AG BC401 15-12 *HQHUDWLQJ'DWD2EMHFWVDW5XQWLPH '$7$UHI^7<3(5()72W\SHBQDPH_/,.(5()72GRBQDPH` &5($7('$7$UHI ó '$7$UHI7<3(5()72GDWD &5($7('$7$UHI7<3(^W\SHBQDPH_LWDEBW\SHBGHI` 3$5$0(7(56SDBWDE7<3(GGWDEQDPH '$7$UHIBLWDE7<3(5()72GDWD <RXFDQDOVR DVVLJQDW\SH G\QDPLFDOO\ × ¡* 0´ &5($7('$7$UHIBLWDE7<3(67$1'$5'7$%/( 2) SDBWDE :,7+'()$8/7.(< 6WDQGDUGWDEOHZLWKVWDQGDUGNH\ DQGOLQHW\SHDSSURSULDWHIRUWKH FRQWHQWRIWKHGDWDREMHFWSDBWDE SAP AG 2002 n All data objects declared in the declaration part of a program using the appropriate statement (such as DATA) are generated statically and can be addressed from when the first event block is executed. However, you can also use data reference variables to generate any data object you want dynamically while the program is executing. You can use either of the above variants to do this. n Both of these variants generate a data object in the internal session of the current ABAP program. The data reference in the data reference variable ref points to this object after the statement has been executed. This dynamically generated data object does not have its own name; it can only be addressed using the data reference variable. If you want to access the content of the data object, you need to dereference the data reference first. n In the second variant, you specify the data type of the data object you want to generate after the TYPE addition of the CREATE-DATA statement. In this case, you can specify the data type dynamically: CREATE DATA ref TYPE (dataobject). You cannot do this in other ABAP statements. dataobject is the name of a field containing the name of the relevant data type. n When you generate internal tables using the second variant, you must specify the table kind statically. You can, however, specify the line type either statically or dynamically. You can also specify the key components either statically or dynamically (as the contents of a table containing the component names). You can also specify the initial number of table lines statically or dynamically (as the contents of a variable). © SAP AG BC401 15-13 'HUHIHUHQFLQJ'DWD5HIHUHQFHV $66,*1UHI! 72IV!>&$67,1*@ 3$5$0(7(56SDBWDE7<3(GGWDEQDPH '$7$UHIBLWDE7<3(5()72GDWD <RXFDQWKHQDGGUHVV WKHFRQWHQWVRIWKH LQWHUQDOWDEOHXVLQJWKH ILHOGV\PERO ã J´ × ¡* 0´ ),(/'6<0%2/6IVBLWDE!7<3($1<7$%/( &5($7('$7$UHIBLWDE7<3(67$1'$5'7$%/( 2) SDBWDE :,7+'()$8/7.(< $66,*1UHIBLWDE! 72IVBLWDE! 6(/(&7 )520 SDBWDE ,1727$%/(IVBLWDE! SAP AG 2002 n To access the contents of the data object, you need to dereference the data reference first. To access data objects generated with data reference variables with generic types (TYPE REF TO data), you can use field symbols: ASSIGN ref->* TO <fs>. This statement assigns the relevant data object (the one to which the data reference in the reference variable ref points) to the field symbol <fs>. If the data object i s assigned successfully, sy-subrc is set to 0. If the field symbol is fully generically typed, it adopts the type of the data object. If the field symbol is partially or completely typed, the system checks the compatibility of the data types. You can also cast to the assigned data object. n If the data reference in ref is initial or invalid, it cannot be dereferenced. In that case the field symbol remains unchanged and sy-subrc is set to 4. n If the data reference variable ref is completely typed (that is, not generically), you can use the prefix ref! to access the contents of the data object to which ref is pointing. You can write this expression in any operand position. If the data reference is typed, you can also address the components of the referenced data object directly and use them in any operand position. DATA ref TYPE REF TO sflight. CREATE DATA ref. ref->fldate = ref->fldate + 5. WRITE: / ref->seatsmax. © SAP AG BC401 15-14 ([DPSOH*HQHUDWLQJ'DWD2EMHFWVDW5XQWLPH 3$5$0(7(56SDBGEWDE7<3(GGOWDEQDPH'()$8/7 6)/,*+7 '$7$GBUHI7<3(5()72GDWD ),(/'6<0%2/6IVBZD!7<3($1<IVBFRPS!7<3($1< 67$572)6(/(&7,21 &5($7('$7$GBUHI7<3( SDBGEWDE $66,*1GBUHI! 72IVBZD! 6(/(&7 )520 SDBGEWDE ,172IVBZD! '2 $66,*1&20321(17V\LQGH[2)6758&785(IVBZD!72IVBFRPS! ,)V\VXEUF1( 6.,3 (;,7 (1',) :5,7(IVBFRPS! (1''2 (1'6(/(&7 SAP AG 2002 n This example displays the content of a transparent table. You can make the FROM clause of the SELECT statement dynamic. For the INTO clause, you will need a data object that has a line type compatible with that of the table being displayed. Since the name - and thus the line type of the table is not known until runtime, you should not create the data object until then. n Unlike conventional data objects, you can specify the type of a data object FUHDWHGDWUXQWLPH dynamically. The TYPE addition of the CREATE DATA statement contains the name of the table, so that the system creates the appropriate structure. n The statement ASSIGN d_ref->* TO <fs_wa> assigns the data object to the field symbol. The data type of the table is inherited by the field symbol, so type casting is no longer necessary. n You can now write each data record from the SELECT statement into the compatibly-typed data object using the field symbol <fs_wa>. n If you knew the component names, you could display the fields directly using WRITE <fs_wa>... . However, you will not normally know the names of the components, nor how many of them there are. For this reason, you must display the components using the ASSIGN-COMPONENT variant: The components of the structure IVBZD are assigned one-by-one to the field symbol IVBFRPS! and then displayed. When the loop runs out of components, the program reads the next data record. © SAP AG BC401 15-15 '\QDPLF3URJUDPPLQJ )LHOG6\PEROVLQ'HWDLO )LHOG6\PEROVLQ'HWDLO '\QDPLF&DOOV '\QDPLF&DOOV 'DWD5HIHUHQFHV 'DWD5HIHUHQFHV $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ $VFHUWDLQLQJ'DWD$WWULEXWHV'\QDPLFDOO\ SAP AG 2002 © SAP AG BC401 15-16 $VFHUWDLQLQJ,QWHUQDO7DEOH$WWULEXWHV '$7$QRBRIBOLQHV7<3(L LQLWLDOBOLQHV7<3(L WDEOHBNLQG7<3(F '(6&5,%(7$%/(LWDE /,1(6QRBRIBOLQHV 2&&856LQLWLDOBOLQHV .,1'WDEOHBNLQG 1XPEHURIOLQHVLQ WKHLQWHUQDOWDEOH 1XPEHURIOLQHV UHVHUYHGZKHQWDEOH ZDVILUVWFUHDWHG 7DEOHNLQG RWKHUYDULDQW QRBRIBOLQHV OLQHV LWDE WDEOHBNLQG &RQVWDQWVXVHG WRHYDOXDWHWKH UHWXUQYDOXH 7<3(322/V\GHV •V\GHVBNLQGXQGHILQHG •V\GHVBNLQGVWDQGDUG •V\GHVBNLQGVRUWHG •V\GHVBNLQGKDVKHG SAP AG 2002 n The DESCRIBE TABLE statement allows you to obtain the following information about an internal table: l The number of lines: After LINES, you must enter a type L variable (here no_of_lines) l The number of table lines initially reserved:After OCCURS, you must enter a type L variable (here: initial_lines) l The table kind: After KIND, you must enter a type F variable. The runtime system fills the variable with a constant defined in the type group SYDES - SYDES_KIND-UNDEFINED, SYDES_KINDSTANDARD, SYDES_KIND-SORTED, or SYDES_KIND-HASHED. n Since SAP R/3 Basis Release 6.10, there is also a built-in function, lines. n 1RWH You can use the information about the number of lines in an internal table to query at runtime whether an internal table has any entries in it at all. Alternatively, use the IS INITIAL query. The generically-typed interface parameters of subroutines, function modules, and methods can use the information on the table kind. © SAP AG BC401 15-17 '\QDPLF7\SH'HVFULSWLRQVIRU577,&ODVVHV +LHUDUFK\RIGHVFULSWLRQFODVVHV 5XOHV S S 7 7 /2 XY S^ ,+ /2T T+/8 /VUUÆ W W [ X UU + S ]] , Z_Z[,,\ \ ^ S S 7 7 /V /2T T+/V /VUÆUÆ Z Z /^/^W W / / Z[Z[,, \ \ S^SY] ] gh"ij k S S 7 7 /2 /VT+T"/V /8UU , , 7 7 , , . . Z[Z_, ,\ \ SYSY] ] v S S 7 7 /2 /VT+T"/V /8UU+ ] ] , , e e ZaZa,,\ \ S2 S0] ] l S S 7 7 /2 S2 -Y /VT+T"/V /8UUS S 5 5 .b . UU 77 ,, ^ b S ]] - ZaZa,,\ \ 0 S S 7 7 /8 /VT"T+/8 /2UUÆ \ \ W+W'][]af)f)SaS_W W ZaZa,,\ \ S^ S2] ] S S 7 7 /8 /VT"T+/8 /2UUÆ WW /2 /VT T 7 7 ,+,)Z[Z_,,\ \ S0 S^] ] l l S S 7 7 /V /2T T+/V /VUÆUÆ 5 5 T)T)` ` , , SaS_W W ZaZ6,,"\ \ S2 S2] ] S S 7 7 /2 S2 \) /VT+T"/V /8UUS S 7 7 / / + S ]] \ \[\_ZaZ_,,\ \ ^ j j k ¦mlã¤on«¤onqp¦k§ ¦mrs ji k j"z lã¦k¦ ¤ot«ª©¦ l*¦wl ¨6t@x q ¦ l㦠q ª n«¦¤Ky j h ¨qual 3DVVWKHGDWDREMHFWWRWKH VWDWLFPHWKRG '(6&5,%(B%<B'$7$RIWKH FODVV&/B$%$3B7<3('(6&5 *HWWKHUHIHUHQFHWRWKH DSSURSULDWHGHVFULSWLRQREMHFW (YDOXDWHWKHSXEOLFDWWULEXWHV RIWKLVREMHFW S S 7 7 /2 /VT+T"/V /8UU "cQcQd)d'W)W+e e ZaZ6,,\ \ S2 S0] ] SAP AG 2002 n Since the introduction of ABAP Objects, there is now a system called the RTTI concept (Run Time Type Information) that you can use to find out type attributes at runtime. It is based on system classes. The concept includes all ABAP types, and so covers all of the functions of the statements DESCRIBE FIELD and DESCRIBE TABLE. n There is a description class for each type with special attributes for special type attributes. The class hierarchy of the description classes corresponds to the hierarchy of the types in the ABAP type system. In addition, the description classes for complex types, references, classes, and interfaces have special methods used to specify references to sub-types. Using these methods, you can navigate through a compound type to all its sub-types. n To obtain a reference to a description object of a type, you must use the static methods of the class CL_ABAP_TYPEDESCR or the navigation methods of the special description class. The description objects are then created from one of the subclasses. At runtime, exactly one description object exists for each type. The attributes of the description object contain information on the attributes of the type. © SAP AG BC401 15-18 'HFODULQJ7\SHV'\QDPLFDOO\([DPSOH '$7$ GHVFUBUHI7<3(5()72FOBDEDSBVWUXFWGHVFU ZDBFRPS7<3(DEDSBFRPSGHVFU 67$572)6(/(&7,21 JHWUHIHUHQFHWRW\SHGHVFULSLRQREMHFWE\ZLGHQLQJFDVW GHVFUBUHI" FOBDEDSBW\SHGHVFU !GHVFULEHBE\BGDWD IVBZD! 7232)3$*( /223$7GHVFUBUHI!FRPSRQHQWV,172ZDBFRPS :5,7(ZDBFRPSQDPH (1'/223 SAP AG 2002 n We can now enhance the example of dynamic type declarations so that the system also displays the column names of the transparent table in the list. n Since we need the attributes of a structure, we first define a reference to the appropriate description class. Instances of this class possess a COMPONENTS attribute, which you use to describe the individual components of the relevant structure. This attribute is an internal table. Therefore you also need to define a work area with a compatible line type. n The (functional) method call returns the reference to the description instance of the structure. (The system creates the structure dynamically, which is why it is accessed through a field symbol). Only the abstract class CL_ABAP_TYPEDESCR contains the method DESCRIBE_BY_DATA. Its RETURNING parameter is typed as a reference to this superclass. However, since the actual parameter descr_ref has the type of the subclass CL_ABAP_STRUCTDESCR, we need to assign the object using a (widening) cast. n You can then access the attributes of the description instance in any form. In this example, the component names are displayed as the column headers. (We have omitted the formatting options for the sake of clarity.) n For more information and syntax examples, refer to the online documentation, either under the keyword 577, or the class CL_ABAP_TYPEDESCR. © SAP AG BC401 15-19 '\QDPLF3URJUDPPLQJ8QLW6XPPDU\ <RXDUHQRZDEOHWR l 8VHG\QDPLFDWWULEXWHVLQVXLWDEOH$%$3 VWDWHPHQWV l 8VHGDWDREMHFWVJHQHUDWHGDWUXQWLPH l $VFHUWDLQWKHDWWULEXWHVRIGDWDREMHFWVDWUXQWLPH SAP AG 2002 © SAP AG BC401 15-20 2SWLRQDO 8QLW '\QDPLF3URJUDPPLQJ 7RSLF&DVWLQJ7\SHV At the conclusion of these exercises, you will be able to: • Use field symbols to cast types • Perform calculations on dates Change your program so that the default value for the key date is calculated differently. It should be the first day of the following month. 3URJUDP 7HPSODWH 6$3%&B7$%6B352&(66B'$7$ 0RGHOVROXWLRQ 1-1 1-2 1-3 © SAP AG =%&BB&$67,1* 6$3%&B'<16B&$67,1* Copy your solution to the last exercise from the unit 8VLQJ,QWHUQDO7DEOHV =%&BB352&(66B'$7$ or the corresponding model solution 6$3%&B7$%6B352&(66B'$7$ and give it the new name =%&BB&$67,1*. Define a structure type (we suggest the name: VWBGDWH) with three components: Year, month, and day. Assign an appropriate type to each component. Define a field symbol based on this type (suggested name: IVBGDWH!). In the /2$'2)352*5$0 event block: Copy today’s date to the input parameter SDBGDWH. Assign the input parameter to the field symbol. Now fill the input parameter with the first day of the next month by accessing the pseudo-components for the year, month, and day, using the field symbol. BC401 15-21 6FUHHQ([HUFLVH 8QLW '\QDPLF3URJUDPPLQJ 7RSLF '\QDPLF2SHQ64/6WDWHPHQWVDQG *HQHUDWLQJ'DWD2EMHFWVDW5XQWLPH At the conclusion of these exercises, you will be able to: • Generate data objects dynamically • Program dynamic SQL statements Develop an ABAP program that can be used as an DGKRF data browser. You should be able to access only the table name on the selection screen. Delegate filtering by field content and similar functions to an SAP Grid Control instance, which you should also use to display the data. The purpose of this program is to make you more familiar with dynamic programming techniques. (There is already a 'DWD%URZVHU, installed as a standard tool in the ABAP Workbench.) =%&BB&5($7(B'$7$B64/ 3URJUDP 7HPSODWH SAPBC401_DYN7_CREATE_DATA_SQL 0RGHOVROXWLRQ SAPBC401_DYN6_CREATE_DATA_SQL 2-1 Copy your program, SAPBC401_DYN7_CREATE_DATA_SQL, giving it the name =%&BB&5($7(B'$7$B64/. 2-2 Get to know the source code and runtime behavior of this program. Then implement the following concept: At runtime, the program should generate an internal table whose line type is compatible with the selected transparent table. The former should then be filled with the complete contents of the latter using a dynamic SQL statement. The internal table filled in this way should then be passed to a SAP Grid Control instance. 2-3 Define a reference for the internal table that will be generated (we suggest the name UHIBLWDE). 2-4 At program runtime, generate the internal table. At this time, it is known which line type must be used. The table must be a standard table with a non-unique standard key. © SAP AG BC401 15-22 2-5 Assign a generically-typed field symbol to the generated internal table (suggested name: IVBLWDE!), so that its contents can be accessed. 2-6 Before calling the screen, insert an Open SQL statement that copies the complete contents of the selected transparent table into the internal table using an array fetch. If an error occurs, make sure the program terminates. 2-7 Generate a SAP Grid Control instance within the PBO module that you have created, ,1,7B&21752/6B. Again, if an error occurs, make sure the program terminates. The relevant class is called &/B*8,B$/9B*5,'. 2-8 Pass the internal table filled in this way to this SAP Grid Control instance. If an error occurs, make sure the program terminates. The relevant method is called 6(7B7$%/(B)25B),567B',63/$<. You need only pass values to two parameters: The line type to ,B6758&785(B1$0( and the name of the internal table to ,7B2877$%. © SAP AG BC401 15-23 6ROXWLRQ2SWLRQDO 8QLW '\QDPLF3URJUDPPLQJ 7RSLF &DVWLQJ7\SHV 5(3257VDSEFBG\QVBFDVWLQJ TYPE-POOLS col. TYPES: BEGIN OF st_flight_c, ... END OF st_flight_c, BEGIN OF st_flight, ... END OF st_flight, %(*,12)VWBGDWH \HDU 7<3(Q PRQWK 7<3(Q GD\ 7<3(Q (1'2)VWBGDWH CONSTANTS c_number TYPE i VALUE 30. DATA: datastring TYPE string, set_string TYPE string, wa_flight_c TYPE st_flight_c, wa_flight © SAP AG TYPE st_flight. BC401 15-24 DATA: it_sets TYPE STANDARD TABLE OF string WITH NON-UNIQUE DEFAULT KEY INITIAL SIZE c_number, it_flights TYPE SORTED TABLE OF st_flight WITH UNIQUE KEY fldate carrid connid INITIAL SIZE c_number, it_doubles TYPE SORTED TABLE OF st_flight WITH NON-UNIQUE KEY fldate carrid connid INITIAL SIZE c_number, it_col_flights TYPE bc401_t_flights_color, it_col_doubles LIKE it_col_flights, wa_col_flight LIKE LINE OF it_col_flights. ),(/'6<0%2/6IVBGDWH!7<3(VWBGDWH PARAMETERS: pa_date LIKE sy-datum, pa_alv AS CHECKBOX DEFAULT ’X’. LOAD-OF-PROGRAM. SDBGDWH V\GDWXP $66,*1SDBGDWH72IVBGDWH!&$67,1* IVBGDWH!GD\ ,)IVBGDWH!PRQWK IVBGDWH!PRQWK IVBGDWH!PRQWK (/6( IVBGDWH!PRQWK IVBGDWH!\HDU IVBGDWH!\HDU (1',) AT SELECTION-SCREEN. IF pa_date < sy-datum. MESSAGE e085(bc401). " date in the past ENDIF. START-OF-SELECTION. ... © SAP AG BC401 15-25 6ROXWLRQ 8QLW '\QDPLF3URJUDPPLQJ 7RSLF '\QDPLF2SHQ64/6WDWHPHQWVDQG*HQHUDWH 'DWD2EMHFWVDW5XQWLPH 2-1 The copy template displays a selection screen where you can enter the name of a transparent table. It then shows a screen that displays the contents of this table. From this screen, you can either navigate back to the selection screen or end the program. This runtime behavior is implemented using standard ABAP programming techniques. A docking container control instance that fills the whole screen has already been generated and attached to the screen. 2 0RGHOVROXWLRQ 6$3%&B'<16B&5($7(B'$7$B64/ REPORT sapbc401_dyns_create_data_sql. DATA: ok_code LIKE sy-ucomm, popans. DATA: ref_docking TYPE REF TO cl_gui_docking_container, UHIBDOY7<3(5()72FOBJXLBDOYBJULG '$7$UHIBLWDE7<3(5()72GDWD ),(/'6<0%2/6IVBLWDE!7<3($1<7$%/( PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT ’SPFLI’. © SAP AG BC401 15-26 START-OF-SELECTION. &5($7('$7$UHIBLWDE7<3(67$1'$5'7$%/(2) SDBWDE :,7+12181,48('()$8/7.(< $66,*1UHIBLWDE! 72IVBLWDE! 6(/(&7 )520 SDBWDE ,1727$%/(IVBLWDE! ,)V\VXEUF! 0(66$*(D UIZ :,7+WH[WQGW (1',) CALL SCREEN 100. *&--------------------------------------------------------* *& Module clear_ok_code OUTPUT * *&--------------------------------------------------------* MODULE clear_ok_code OUTPUT. CLEAR ok_code. ENDMODULE. " clear_ok_code OUTPUT *&--------------------------------------------------------* *& Module STATUS_0100 OUTPUT * *&--------------------------------------------------------* MODULE status_0100 OUTPUT. SET PF-STATUS ’ST100’. SET TITLEBAR ’T100’. ENDMODULE. " STATUS_0100 OUTPUT *&--------------------------------------------------------* *& Module init_controls_0100 OUTPUT * *&--------------------------------------------------------* MODULE init_controls_0100 OUTPUT. IF ref_docking IS INITIAL. * CREATE OBJECT ref_docking EXPORTING SIDE extension EXCEPTIONS OTHERS . IF sy-subrc <> 0. MESSAGE a015(rfw). ENDIF. &5($7(2%-(&7UHIBDOY (;3257,1* LBSDUHQW (;&(37,216 HUURUBFQWOBFUHDWH HUURUBFQWOBLQLW HUURUBFQWOBOLQN HUURUBGSBFUHDWH 27+(56 © SAP AG = DOCK_AT_LEFT = 2000 = 6 UHIBGRFNLQJ BC401 15-27 ,)V\VXEUF! 0(66$*(D UIZ :,7+WH[WDHU (1',) &$//0(7+2'UHIBDOY!VHWBWDEOHBIRUBILUVWBGLVSOD\ (;3257,1* LBVWUXFWXUHBQDPH SDBWDE &+$1*,1* LWBRXWWDE IVBLWDE! (;&(37,216 LQYDOLGBSDUDPHWHUBFRPELQDWLRQ SURJUDPBHUURU WRRBPDQ\BOLQHV 27+(56 ,)V\VXEUF! 0(66$*(D UIZ (1',) ENDIF. ENDMODULE. " init_controls_0100 OUTPUT *&--------------------------------------------------------* *& Module leave_programm INPUT * *&--------------------------------------------------------* MODULE leave_programm INPUT. CLEAR popans. CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’ EXPORTING textline1 = text-dml textline2 = text-rcn titel = text-cnc cancel_display = ’ ’ IMPORTING answer = popans. CASE popans. WHEN ’J’. LEAVE PROGRAM. WHEN ’N’. CLEAR ok_code. ENDCASE. ENDMODULE. " leave_programm INPUT © SAP AG BC401 15-28 *&--------------------------------------------------------* *& Module user_command_0100 * *&--------------------------------------------------------* MODULE user_command_0100 INPUT. CASE ok_code. WHEN ’BACK’. CLEAR popans. CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’ EXPORTING textline1 = text-dml textline2 = text-rbk titel = text-bak cancel_display = ’ ’ IMPORTING answer = popans. CASE popans. WHEN ’J’. LEAVE TO SCREEN 0. WHEN ’N’. ENDCASE. WHEN OTHERS. ENDCASE. © SAP AG BC401 15-29