6$3-6()XQGDPHQWDOV -$ 6$3-6()XQGDPHQWDOV SAP AG 2007 SAP AG©2006 SAP NetWeaver 2004s 2006/Q3 Material number: 50085582 &RS\ULJKW &RS\ULJKW 6$3$*$OOULJKWVUHVHUYHG 1RSDUWRIWKLVSXEOLFDWLRQPD\EHUHSURGXFHGRUWUDQVPLWWHGLQ DQ\IRUPRUIRUDQ\SXUSRVHZLWKRXWWKHH[SUHVVSHUPLVVLRQRI 6$3$*7KHLQIRUPDWLRQFRQWDLQHGKHUHLQPD\EHFKDQJHG ZLWKRXWSULRUQRWLFH SAP AG 2006 Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, System i, System i5, System p, System p5, System x, System z, System z9, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, Informix, i5/OS, POWER, POWER5, POWER5+, OpenPower and PowerPC are trademarks or registered trademarks of IBM Corporation. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated in the United States and/or other countries. Oracle is a registered trademark of Oracle Corporation. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc. HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Java is a registered trademark of Sun Microsystems, Inc. … … JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. MaxDB is a trademark of MySQL AB, Sweden. SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. The information in this document is proprietary to SAP. No part of this document may be reproduced, copied, or transmitted in any form or for any purpose without the express prior written permission of SAP AG. This document is a preliminary version and not subject to your license agreement or any other agreement with SAP. This document contains only intended strategies, developments, and functionalities of the SAP® product and is not intended to be binding upon SAP to any particular course of business, product strategy, and/or development. Please note that this document is subject to change and may be changed by SAP at any time without notice. SAP assumes no responsibility for errors or omissions in this document. SAP does not warrant the accuracy or completeness of the information, text, graphics, links, or other items contained within this material. This document is provided without a warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP shall have no liability for damages of any kind including without limitation direct, special, indirect, or consequential damages that may result from the use of these materials. This limitation shall not apply in cases of intent or gross negligence. The statutory liability for personal injury and defective products is not affected. SAP has no control over the information that you may access through the use of hot links contained in these materials and does not endorse your use of third-party Web pages nor provide any warranty whatsoever relating to third-party Web pages. &RXUVH3UHUHTXLVLWHV 5HTXLUHG 3URJUDPPLQJH[SHULHQFHLQDQ\ SURJUDPPLQJODQJXDJH %DVLFNQRZOHGJHRIUHPRWHFDSDEOHIXQFWLRQ PRGXOHVDQG%$3,V 5HFRPPHQGHG .QRZOHGJHRIWKHREMHFWRULHQWHGSURJUDPPLQJ SAP AG 2004 7DEOHRI&RQWHQWV Unit 1 ,QWURGXFWLRQ Unit 6 ([FHSWLRQV Unit 2 'DWD7\SHV Unit 7 Unit 3 ([SUHVVLRQVDQG6WDWHPHQWV ,QWURGXFWLRQWR &ROOHFWLRQ)UDPHZRUN Unit 4 2EMHFW2ULHQWHG3URJUDPPLQJ Unit 8 ,QWURGXFWLRQWR6$3 &RQQHFWLYLW\ Unit 5 ,QKHULWDQFHDQG,QWHUIDFHV Unit 9 -((3UHYLHZ $SSHQGL[ SAP AG 2004 ,QWURGXFWLRQ &RQWHQWV z ,QWHJUDWLRQRI-DYDLQWKH6$3:HE$SSOLFDWLRQ6HUYHU z 6WUXFWXUHRIWKH-DYDSURJUDPPLQJODQJXDJH z ,QVWDOOLQJWKH-DYD6RIWZDUH'HYHORSPHQW.LW -6'. z &UHDWLQJDVLPSOH-DYDDSSOLFDWLRQ SAP AG 2004 © SAP AG JA100 1-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z ([SODLQWKHUROHRI-DYDLQWKH6$31HW:HDYHU HQYLURQPHQW z 'HVFULEHWKHSURSHUWLHVRI-DYD z 'HVFULEHWKHVWUXFWXUHRID-DYDSURJUDP z ,QVWDOOWKH-6'. z &UHDWHFRPSLOHDQGH[HFXWHDVLPSOH -DYDSURJUDP SAP AG 2004 © SAP AG JA100 1-2 6$3:HE$SSOLFDWLRQ6HUYHU 7KH 6$3:HE$SSOLFDWLRQ 6HUYHU LQWHJUDWHVD-DYD VWDFNLQWRWKHWHFKQRORJLFDO EDVLVRIWKH6$3V\VWHP SAP AG 2004 © SAP AG JA100 1-3 8VLQJ-DYDLQ6$3$SSOLFDWLRQV z 6$3HEXVLQHVVDSSOLFDWLRQV P\6$3 &50P\6$3 650DQGVR RQ 6$3,QWHUQHW6DOHV '\QDPLF3ULFLQJ(QJLQH ,QWHUQHW&XVWRPHU6HOI6HUYLFH ,QWHUQHW3ULFLQJDQG &RQILJXUDWRU z /LYH:HE&ROODERUDWLRQ 6$3(QWHUSULVH3RUWDO &RUH(QWHUSULVH3RUWDO SODWIRUP -DYDEDVHGLQIUDVWUXFWXUHIRU WKHSUHVHQWDWLRQOD\HU z &RQWHQW0DQDJHPHQW 6$3([FKDQJH,QIUDVWUXFWXUH ,QWHJUDWLRQ5HSRVLWRU\ ,QWHJUDWLRQ'LUHFWRU\ SAP AG 2004 SAP already delivers many applications based on Java or J2EE. © SAP AG JA100 1-4 6$3%XVLQHVV&RQQHFWRU 6$3%XVLQHVV&RQQHFWRU 0LGGOHZDUHXVHGWRH[FKDQJH;0/GRFXPHQWV ;0/ 3URJUDPPHGLQ-DYDXVHVWKH6$3-DYD &RQQHFWRULQWHUQDOO\ 7KHGHYHORSPHQWHQYLURQPHQW 6$3%XVLQHVV&RQQHFWRU 'HYHORSHU HQDEOHV\RXWR 6$3 6$3 6\VWHP 6\VWHP 0DSHOHPHQWVJUDSKLFDOO\EHWZHHQ;0/ILOHV 0RGHOIORZVHUYLFHVJUDSKLFDOO\ &UHDWHDQGXVH:HEVHUYLFHV XVLQJ:6'/ 'HOLYHUHGIUHHZLWKDOO6$3FRPSRQHQWV )RUPRUHLQIRUPDWLRQVHHWKH6$36HUYLFH 0DUNHWSODFH SAP AG 2004 KWWSVHUYLFHVDSFRPFRQQHFWRUV The SAP Business Connectorlets you map different structures, for example, different XML structures. © SAP AG JA100 1-5 6$3-DYD&RQQHFWRU 6$3-DYD&RQQHFWRU -&R (QDEOHV6$3V\VWHPVDQG-DYDDSSOLFDWLRQVWRFRPPXQLFDWH 6$3 6$3 6\VWHP 6\VWHP 0!!#"$! ! !$%$&%&%&'1')( *#!#+,( -/. . 6XSSRUWVERWKLQERXQGFRPPXQLFDWLRQ ZKHUH-DYDFDOOV$%$3 DQG RXWERXQGFRPPXQLFDWLRQ ZKHUH$%$3FDOOV-DYD +LGHVWKHDZNZDUGDVSHFWVRISURJUDPPLQJIURPWKHGHYHORSHU LQFOXGLQJFRGHSDJHVGDWDW\SHFRQYHUVLRQVDQGFRQQHFWLRQSRROV *XDUDQWHHVJRRGSHUIRUPDQFHE\RSWLPL]LQJWKHVRXUFHFRGH SAP AG 2004 -DYD&RQQHFWRU -&R The SAP Business Connector is based on the SAP Java Connector. © SAP AG JA100 1-6 &RPSDUH $%$3DQG-DYD 7KH 6$3:HE$SSOLFDWLRQ 6HUYHUHQDEOHV \RX WR FUHDWHDSSOLFDWLRQVXVLQJ$%$3RU-DYD z $%$3DQG -DYD $%$3%RWKREMHFWRULHQWHGDQG SURFHGXUDO -DYD2EMHFWRULHQWHG $%$3DQG-DYD%RWKFURVVSODWIRUP ZULWHRQFHUXQDQ\ZKHUH 235467/28:9<; = $%$3DQG-DYD6RXUFHFRGH FRQYHUWHGWRSVHXGRFRGHZKHQ FRPSLOHGWKHQLQWHUSUHWHGE\YLUWXDO PDFKLQH 90 $%$3DQG-DYD90DYDLODEOHIRUDOO DSSURSULDWHRSHUDWLQJV\VWHPV SAP AG 2004 © SAP AG JA100 1-7 -DYD/DQJXDJH'HVLJQ -DYDDVDSURJUDPPLQJODQJXDJHVKRXOGEH z z 6LPSOH 6LPSOH z z 2EMHFWRULHQWHG 2EMHFWRULHQWHG z z 'LVWULEXWHG 'LVWULEXWHG z z ,QWHUSUHWHG ,QWHUSUHWHG z z 5REXVW 5REXVW z z 6HFXUH 6HFXUH z z 1HXWUDODUFKLWHFWXUH 1HXWUDODUFKLWHFWXUH z z 3RUWDEOH 3RUWDEOH SAP AG 2004 Simple Java is a programming language with advanced features and is easier to learn than C or C++. Object-oriented Java is a FRPSOHWHO\object-oriented, language unlike C++. Distributed Java implements numerous functions for the use of any logs and services in standard libraries. Interpreted The YLUWXDOPDFKLQHperforms the role of interpreter in Java. It is software that must be developed separately for each platform and, therefore, creates an interface between the platform-independent bytecode and the respective system. Robust Java does not use pointers to address and manipulate memory locations directly. In C and C++, these are one of the main causes of system crashes. Secure The interpreters that have been integrated in the Web browsers prevent Java applications (applets) from accessing the local file system or unprotected memory areas (VDQGER[procedure). Architecture-neutral in contrast to C programs, Java programs do not need to be recompiled if they are to be executed on a new platform. © SAP AG JA100 1-8 -DYD/DQJXDJH'HVLJQ Source Source text text Compiler Compiler And And linker linker Executable Executable file file Interpreter Interpreter Target Target computer computer 3& &RPSLOHG SURJUDPV 0$& 8QL[ 3& ,QWHUSUHWHG SURJUDPV 0$& 8QL[ -DYDSURJUDPV >@?BA C DFEHG C .java file .class file 90 90 90 3& 0$& 8QL[ SAP AG 2004 Compiled programs The compiler first checks that a source file contains the correct syntax, then generates a native code, which is added to an executable file by a linker. + Very fast, since translation only performed once by the developer - Can only be run on the system platform (operating system) on which it is translated. Interpreted programs The interpreter imports the source text during execution and converts this to a native code, which can then be executed. + Faster program development - Slower execution - Syntax error can only be identified during runtime Java: Bytecode and virtual machines Java programs are first compiled. The bytecode created (which cannot be executed in isolation) is then interpreted and executed by a virtual machine, which should be specifically developed for each platform. + Cross-platform, portable - Runs slower © SAP AG JA100 1-9 -6'. 7RROV I<J0KMLN)O PRQN KSP T<UV#WXN KP jo Z,}:} ] Z cdb` YZ5[Z pqBr b:aH] c@b pqBr b:aH] c@b s b@`tn u1n b@` YZ5[Z pqBr b:aH] c@b Y:Z5[@Z \^]_^`1a:b:aH] cdb e1f ghZ5[HZi Y@Z5[Z jk]dlm@n o b` YZF[@Zs n ` r _ Z o ~zZ a@ n { b :Y Z5[@Z p#qBr b:a:] c b e1f a o ZF}H}@i yzmb@` ZFr n {| \ q,}Hr bl 5:FFX F¡X5FB,Xk, d Bw v0Z `wc5x Z ` b t: tdd h@d tdd ^ @ t: t: tdd SAP AG 2004 © SAP AG JA100 3& 0$& 8QL[ 1-10 -6'.7RROV z The compiler: javac MDYDF >RSWLRQV@ILOHOLVW! z The interpreter: Java MDYD >RSWLRQV@FODVV!>SURJUDPDUJXPHQWV@ z Automatic documentation: Javadoc MDYDGRF >RSWLRQV@ILOHQDPH_SDFNDJHQDPH! t h^ t: h^ @ h h w^ 3& 0$& 8QL[ SAP AG 2006 The Java 2 Software Development Kit (J2SDK) includes a range of tools that can be used to develop Java programs. The two most important tools are the javac compiler and the Java interpreter. The programs are located in the bin subdirectory of the SDK installation directory. © SAP AG JA100 1-11 -6'. ,QVWDOODWLRQ Downloading the Java Development Kit SAP AG 2004 The J2SDK can be downloaded from Sun Microsystems at the following URL: KWWSZZZMDYDVRIWFRP © SAP AG JA100 1-12 -6'. ,QVWDOODWLRQ Downloading the API documentation SAP AG 2004 The Java Application Programming Interface (API) describes standard Java classes and packages. It must be downloaded and installed separately. © SAP AG JA100 1-13 -6'. ,QVWDOODWLRQ Setting environment variables 3$7+variable (optional) The directory in which the Java tools are located is entered. &/$663$7+variable (optional) Specifies the directories in which a search for classes and packages is to be performed. -$9$B+20(Yariable (optional) Specifies in which directory the J2SDK was installed. SAP AG 2004 © SAP AG JA100 1-14 3URJUDP6WUXFWXUH º0»^¼d½#»¾¿ ¼^ÀÁ B­  » º ­BÃ Ä »^ÅÆ#Å Æ^¾ ­ ¿Ç#¼ÈÉzÊ ¬¬ËÌÄÎÍ Å ÄÂ^ÃÐÏ »^ѻλººÒ^Åd¼^» à ÅÀÆ º Ì Ó Òżμһ Â^Â Ô ¿ÒÒÀÕ0À Ä Ò ÖØ× ¬²²@ÙdÚ Ú Ú Ú ¿ÛÁ0»#Å^ÆÛÁ0¿ à ÀÖÜÅ ÂÝà ¿Î¿Æ Ã^Ä Þ ºkÀÅ Æ Ã Å^Æ Ã À à ¿ »º^ºkÒ^Åd¼» à ÅdÀÆ ²d¬ º Ì@Ó Ò^ż Âà » à Åd¼ßÑ#ÀÅdÖ Á$»ÅdÆáàâ ÃdÄ Å Æ¾ãäå» Ä ¾ Â#æ × ¬²Fç Åd»èâ ÞÂ^à ¿Á ­ À Ìí º Ä ÅdÆ Ú Ã ÒÆà ­^­^­,æ »dÆéÀ Ì$à º Ì0à Š Å@ÁºÒd¿@Á¿Æ à ¿^ÖèÀÆ Ã ¿Ü¼ÀÆ Â À#Òd¿ ­ ²¬ â ÞkÂ^à ¿ Á ­ À Ìí º Ä Å Æ Ã ÒdÆáà,ê Ô ¿#ÒÒdÀßÕÀ Ä ÒdÖkê æ Ê ë ë -DYDFRPPHQWV ¢¤£z¥M¥¦$§0¨©)ª1§¦$« ¬¬®­^­^­ ¢¤£z¥M¥¦$§0¨¯&© £&°±« ¬#²³­^­^­ ²^¬ ´µ¶$µ0· £$°¸°#£z¥M¥M¦§¨/¯&© £&°k±0« ¹ ¬#²²®­^­^­ ²^¬ SAP AG 2004 Program structure The example above demonstrates the structure of a typical Java class. The source code is saved in a file that has the same name as the class. The data extension is .java. © SAP AG JA100 1-15 3DFNDJHV z Groups of programs can be combined into packages. z You assign a class to a package using the package statement. z If you use the package statement, it must be in the first line of the source code. z Programs can signal the use of º»¼^½»d¾^¿ ¼^ÀÁ ­, »dº ­,Ã Ä »ÅdÆÅÆ^¾ ­ ¿Ç#¼#ÈÉ&Ê Ú Å:ÁºkÀ Ä#à ¼ÀÁ ­B »º ­BÃ Ä »ÅdÆ#Šƾ ­ ¿dÇ#Ú¼È@ì ­Ë0à ¿ Äí Ò» Â^Â Ê Å:ÁºkÀ Ä#à ¼ÀÁ ­B »º ­BÃ Ä »ÅdÆ#Šƾ ­ À à ¿ Ä#î »¼½0»¾^¿ ­² Ê other classes and complete packages using the import statement. z Classes are uniquely identified using a combination of the package º Ì@Ó Ò^Åd¼Ü¼^Ò» ÂÂ Ô ¿Ò^ÒÀÕÀ Ä ÒÖØ× Ú ¬¬Ìk ¿ÜÀ à ¿ Ä ¼Ò» Â^ ¿  ­­^­ ë statement and the classpath environment variable. SAP AG 2004 3DFNDJHV Packages are one way of organizing groups of classes according to their meaning, usage, or inheritance. Java uses the concept of packages to hide the file system for the respective platform. &UHDWLQJ\RXURZQSDFNDJHV y Step 1: Choose a name for your package - The name should be based on the classes it contains. - SUN advises you to reverse the Internet domain name (for example, sap.com). y Step 2: Add classes to the package - Assign a class to a package using the SDFNDJH command. - The package command must be in the first line of the source code (after comments, but before the import statements). © SAP AG JA100 1-16 &RPSLOHDQG([HFXWHD-DYD$SSOLFDWLRQ &RPSLOHVRXUFHFRGH ([HFXWHDSSOLFDWLRQ &UHDWHGRFXPHQWDWLRQ t: tdd h@d tdd ^ @ t: t: tdd 3& 0$& 8QL[ SAP AG 2004 The MDYDF compiler creates a file with the ending “class” from the Java program “HelloWorld.java”. This file contains the bytecode. Via this, the application is executed with the help of the -DYD interpreter. © SAP AG JA100 1-17 6XPPDU\ <RXVKRXOGQRZEHDEOHWR z z z z z ([SODLQWKHUROHRI-DYDLQWKH6$31HW:HDYHU HQYLURQPHQW 'HVFULEHWKHSURSHUWLHVRI-DYD 'HVFULEHWKHVWUXFWXUHRID-DYDSURJUDP ,QVWDOOWKH-6'. &UHDWHFRPSLOHDQGH[HFXWHDVLPSOH -DYDSURJUDP SAP AG 2004 © SAP AG JA100 1-18 ,QWURGXFWLRQ([HUFLVH 2SWLRQDO 8QLW ,QWURGXFWLRQ 7RSLF &RPSLOLQJDQG6WDUWLQJ-DYD3URJUDPV At the conclusion of this exercise, you will be able to: • Compile and execute a preprogrammed example program • Create html documentation for this example program with the help of Javadoc 1-1 Open the command prompt and go to the 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LWdirectory. 1-2 Compile the 6WDUW:LWKMDYD program, which is in the FRPVDSWUDLQLQJH[F package in the 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LW directory. 1-3 Execute the program from the 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LW directory. 1-4 In the command prompt, change to the 1?0\ 'RFXPHQWV?-$[[[?6WDUW8S.LW?FRP?VDS?WUDLQLQJ?H[F directory. From this directory, use the Javadoc tool to create an html documentation for the class 6WDUW:LWKMDYD. Using Microsoft Windows Explorer, open the new file LQGH[KWPO in the 1?0\ 'RFXPHQWV?-$[[[?6WDUW8S.LW?FRP?VDS?WUDLQLQJ?H[F directory by double-clicking on it. © SAP AG JA100 1-19 © SAP AG JA100 1-20 ,QWURGXFWLRQ6ROXWLRQ 2SWLRQDO 8QLW ,QWURGXFWLRQ 7RSLF &RPSLOLQJDQG6WDUWLQJ-DYD3URJUDPV 1-1 Open the command prompt and go to the 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LW directory. 1-2 Change to the directory 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LW and compile the program 6WDUW:LWKMDYD. 1!FG0\'RFXPHQWV?-$[[[?6WDUW8S.LW 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LW!MDYDF ?FRP?VDS?WUDLQLQJ?H[F?6WDUW:LWKMDYD 1-3 Execute the program 6WDUW:LWKMDYD. 1-4 Use Javadoc to create an html documentation for the class 6WDUW:LWKMDYD. 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LW!MDYD FRPVDSWUDLQLQJH[F6WDUW:LWK 1?0\'RFXPHQWV?-$[[[?6WDUW8S.LW?FRP?VDS?WUDLQLQJ?H[F! MDYDGRF6WDUW:LWKMDYD © SAP AG JA100 1-21 © SAP AG JA100 1-22 ([HUFLVH 8QLW ,QWURGXFWLRQ 7RSLF :RUNLQJZLWKWKH'HYHORSPHQW (QYLURQPHQW At the conclusion of this exercise, you will be able to: • Start the development environment • Enhance, compile, and execute a Java application using the development environment 2-1 Start the development environment. 2-2 You will find the 6WDUW8S.LW project in the package explorer of the development environment. The 6WDUW:LWKMDYDfile is in the FRPVDSWUDLQLQJH[Fpackage. Open the 6WDUW:LWKMDYD file in the development environment. 2-3 Replace the comment line “ // WREHUHSODFHG!” with an output statement of your choice, for example: 6\VWHPRXWSULQWOQ ³0\ILUVWVWHSVZLWKWKH'HYHORSPHQW (QYLURQPHQW´ 2-4 Save the program and execute it. © SAP AG JA100 1-23 © SAP AG JA100 1-24 'DWD7\SHV &RQWHQWV z 6LPSOHGDWDW\SHV z 5HIHUHQFHGDWDW\SHV z ([SOLFLWW\SHFRQYHUVLRQV z $UUD\V z 9DULDEOHVDQGFRQVWDQWV SAP AG 2004 © SAP AG JA100 2-1 'DWD7\SHV8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z 'HVFULEHWKHEDVLF-DYDGDWDW\SHV z 'HFODUHYDULDEOHVDQGFRQVWDQWV z 'HILQHDQGXVHDUUD\V z ([SODLQWKHGLIIHUHQFHEHWZHHQVLPSOHDQGUHIHUHQWLDO GDWDW\SHV z &RQYHUWGDWDW\SHV SAP AG 2006 © SAP AG JA100 2-2 2YHUYLHZ'DWD7\SHV FKDU E\WH LQW 6LPSOH GDWDW\SHV 6WULQJ VKRUW ORQJ 5HIHUHQFHGDWDW\SHV XVHUGHILQHG RU GHIDXOW ,QWHUIDFHV ERROHDQ IORDW GRXEOH &ODVVHV $UUD\V SAP AG 2004 The Java virtual machine reserves memory space for simple data types based on the declaration and uses a default value for them. In Java, the type VWULQJ, known in other programming languages, is not a simple data type but a special case. There are no simple types for time and date. © SAP AG JA100 2-3 6LPSOH'DWD7\SHVLQ-DYD 7\SH &RQWHQWV %RROHDQ WUXHor IDOVH Characters from FKDU Unicode table E\WH Integer 'HIDXOW 6L]H >ELW@ false 1 - EODQN! 16 - 0 8 VKRUW Integer 0 16 LQW Integer 0 32 ORQJ Integer 0 64 Floating point number Floating point number 0 32 0 64 IORDW GRXEOH 0LQLPXP 0D[LPXP9DOXH - 128 - 32768 + 127 + 32767 - 2147483648 + 2147483647 - 9.22 * 10 ^ 18 + 9.22 * 10 ^ 18 r 1.40 * 10 ^ -45 r 3.40 * 10 ^ +38 r 4.94 * 10 ^ -324 r 1.79 * 10 ^ +308 SAP AG 2004 © SAP AG JA100 2-4 %RROHDQ7\SH z $%RROHDQ UHSUHVHQWVDGRXEOHYDOXHYDULDEOH DQGFRQWDLQVHLWKHU IDOVH RU WUXH z 'HFODUDWLRQ !"$#% &')(+*,.-/ -0-1325412768$':9$; z ([DPSOH'HFODUDWLRQDQGDVVLJQPHQW SAP AG 2004 © SAP AG JA100 2-5 FKDU7\SH z $FKDUYDULDEOHFRQWDLQVDVLQJOHGRXEOHE\WHV\PEROIURPD 8QLFRGHWDEOH z 'HFODUDWLRQ PQ R:"$# %3&S'T(E*,.-/-.0-B1325417268$':9; z ([DPSOH <= < < 5>@?A>B < 5>JI > CCEDF G <= H < CC < K ELMF N O SAP AG 2004 © SAP AG JA100 2-6 (VFDSH6HTXHQFHV (VFDSHVHTXHQFHVDUHXVHGIRUWH[WRXWSXW \b \t \n \f \r \" \’ \\ \uNNNN Backspace BS Horizontal tab HAT New line (line feed) LF Form feed FF Carriage return CR Quotation mark " Apostrophe ’ Backslash \ Unicode character, e.g. \u0041 (hex.) for A UV D BWYXZ$X\[ F H ] ^_` I < W`IH < WaI _aIH < W`I < Wa^ b. cedfhg cedfon iBdHj k lAm g iBdHj k lAm g idHj klAmn idHj klAmn SAP AG 2004 Unicode characters are replaced before compilation (preprocessing). © SAP AG JA100 2-7 8QLFRGH 1R ... &KDUDFWHU ... 0020 <Space> 0021 ! 0022 “ ... µ?X8QLFRGH1XPEHU!µ ([DPSOH 1 2 3 4 ... CC < FDp = rqHF sW Ot]Z^bu <= Brv>JIBxwwa ao>B CC < FDp = ry < zWHF 7u B {v>JIw waH`$> SAP AG 2004 Unicode is a standard for characters based on two-byte codes. For a list of all characters and corresponding codes, see KWWSZZZXQLFRGHRUJFKDUWV. The code is hexadecimal (example: 007E). Unicode characters are identified in the source code starting with “\u”, followed by the four-digit character code. © SAP AG JA100 2-8 E\WHVKRUWLQWDQGORQJ7\SHV z E\WHVKRUWLQWDQGORQJDUHLQWHJHUW\SHV z 7\SHFKDUFDQDOVREHXVHGDVDQLQWHJHU z 'HFODUDWLRQV x|} ".# % &H'T(~$-/-0- 1$254 126 8.':97; Q RS}".# % &H'T(~$-/-0- 1$254 126 8.':97; .} ".# % &H'T(~$-/-0- 1$254 126 8.':97; ".# % &H'T(~$-/-0- 1$254 126 8.':97; SAP AG 2004 © SAP AG JA100 2-9 )ORDWDQG'RXEOH7\SHV z 6SHFLDOYDOXHVDUHUHVHUYHGIRUIORDWDQGGRXEOHW\SHVZKLFK DSSHDUDVWKHUHVXOWRIFHUWDLQPDWKHPDWLFDORSHUDWLRQV SRVLWLYHDQGQHJDWLYHLQILQLW\SRVLWLYHDQGQHJDWLYH]HUR DQG³QRWDQXPEHU´ 1D1 z 'HFODUDWLRQ x} H"x#%&x'(~Z.}S.- /3-0-B172x4 12768'9o; x} H"x#%&x'(~.-/Y-.0S-z132.4 126 8.'S!9$; 5 SHSSH"x#%&x'(~.-/Y-.0S-z132.4 126 8.':97; SAP AG 2004 © SAP AG JA100 2-10 )ORDWDQG'RXEOH7\SHV z /LWHUDOVRIIORDWLQJSRLQWW\SHVDUHUHFRJQL]HGDVGRXEOHE\ WKHFRPSLOHU z 7KHUHIRUHLQLWLDOL]DWLRQPXVWEHIROORZHGE\³I´ RUSUHFHGHG E\³ IORDW ´ z ([DPSOHRIWKHLQLWLDOL]DWLRQRIIORDWLQJSRLQWW\SHV L H L FHGB[ F Hs`a $XL$ CCB L H L H F GB[ F{5] LH b` a$X. L H LH F GB[ F{`a$X. C CrKH FHDrzW [SF H SAP AG 2004 © SAP AG JA100 2-11 7\SH&RQYHUVLRQ ,IQHFHVVDU\QXPHULFGDWDW\SHVFDQEHFRQYHUWHGIURPRQHW\SH WRDQRWKHU 7KHUHDUHWZRFRQYHUVLRQW\SHV :LGHQLQJ FRQYHUVLRQ E\WH FRQYHUVLRQWRDGDWDW\SHZLWKD ODUJHUYDOXHUDQJH VKRUW ORQJ LQW IORDW GRXEOH FKDU 1DUURZLQJ FRQYHUVLRQ FRQYHUVLRQWRDGDWDW\SHZLWKD VPDOOHUYDOXHUDQJH L ~!xY¡¢; F £; ¤~ FS ¥h; SAP AG 2004 Widening conversion A widening conversion is executed automatically by the compiler, if necessary. This occurs, for example, during the transfer of arguments to methods and during assignments. The direction of an implicit conversion is indicated by the arrows, as shown in the example above. Since the data type char is generally a non-negative number (value range 0 - 2^16-1), it can be converted into an integer data type. Narrowing conversion You can only explicitly achieve a conversion that narrows the value area by placing the desired data types in brackets in front of the respective variable or constant. A narrowing conversion may result in a reduced accuracy. © SAP AG JA100 2-12 6LPSOH'DWD7\SHVYV 5HIHUHQFH'DWD7\SHV 5HIHUHQFHGDWDW\SHV 6LPSOHGDWDW\SHV º ¨»®²°@±´ª ¼A®½®¾¶H§«Sª¿À³ ¶ «H«©H«ªÁ@±¨J©S® µ ¶ ¹ ©H« ¦H§¨J©ª«.¬­®¯¨ª°@±¨²ª³ ­±´ µ ³ ­x¶¨²ª·­x¸.¦³ © ¦­.­$³ ©H¶x± ¹ ¬¶S® ([DPSOH ([DPSOH H} String s = “Java“; hugo = 4; 0HPRU\ 0HPRU\ KXJR V -DYD SAP AG 2004 If a variable is declared by a simple data type, memory space is immediately made available for it. Here, the content of the variable is linked inseparably with the variable name. That means that the content can only be changed via the variable. A reference data type is a data type in which variables of its type do not contain the actual data or contents, but contain a reference to the memory location for the data. Thus, several reference variables can point to the same content. In particular, the referenced content can be changed via different variables. © SAP AG JA100 2-13 'DWD 7\SH6WULQJ z 'HODUDWLRQ DQGLQVWDQWLDWLRQ ÆÆÎÍx P SSR.x}SvÌ Â }R..  }Rx.ÌÈSR$S ; ÆSÆ É RS},  }SRx, YÏ P } ~ ÃÐ Q }RHÑ+à ; z 6WULQJVFDQFRQWDLQ(VFDSHDQG8QLFRGHVHTXHQFHV Æ.ÆÓÒ SR} ÃÐÔ7à PQ R P } RÓ:} Q  }SRSS  }R.. ~ ÃÐ Q ¥P R ÕËoRH S} } Q ÂÖo×xØ xÄ3 Ä.ÄÓ}¥|xx£Ùà ; z &DXWLRQ 6WULQJVFDQ127EHFRQYHUWHGE\DGLUHFWFDVWLQQXPHULFDOW\SHV  }R.x ~ ÃHÄÅS¡Ã ; F ¥~ F bD ; ÆÆÇÈ.R ¥É ÊË7xSRÌxR.RR SAP AG 2004 © SAP AG JA100 2-14 $UUD\V )LHOGV ([DPSOH/RWWHU\QXPEHUV 3RVLWLRQ 9DOXH LQW SAP AG 2004 An array is a data structure of fixed size that consists of elements of the same type. Arrays contain several variables of one type and can be accessed using indexes. Arrays can be created for every data type (including non-simple types). The field size of arrays is specified during initialization, after which it can only be reset by deleting the complete array contents. Arrays can have several dimensions in which they store their values. © SAP AG JA100 2-15 'HFODULQJDQG&UHDWLQJ$UUD\V z $UUD\VDUHFUHDWHGE\XVLQJWKHNH\ZRUGQHZ z 'HFODUDWLRQH[DPSOHV } .HÊxxR (9; HÊ..$R ~ xÛ53} (zÜ.9$; ÆÆÚËx$RÓ P .Rx}Sx ÆÆ P RSx}x H} .Ý(9~ xÛ5.} (ÞÜ$9$; ÆƤÍx P xR$}x,x P RSS$}x H} (z9.xÓ~ xÛ5.} (ÞÜ$9$; ÆƤÍx P xR$}x,x P RSS$}x SAP AG 2004 © SAP AG JA100 2-16 $FFHVVWR$UUD\V z 1RWHWKDWWKHLQGH[RIWKHILUVWHOHPHQWLVDOZD\V x|$} Sxß(z9~ .ÛS|o} (Å79$; $Hå(æ39~tÀ; ÆSÆ¥.R }ÎÊ..} $Hå(»9~vÄç; $Hå(²Ä 9~Å; z $UUD\VFDQDOVREHFUHDWHGDVIROORZV x|$} LGHQWLFDO Sxß(z9~áàHoâzÄAâãÅYä.; SAP AG 2004 © SAP AG JA100 2-17 $FFHVVWR$UUD\V z 7KHOHQJWKRIDQDUUD\UHWXUQVWKH³OHQJWK´ SURSHUW\ 1 2 3 4 S|} Êx| Ö RSRxH|î(z9~ïàÄ.¡ âÜ Ä£âzoä; H} S.ðS Ö RRxH|,~ÇÊ$| Ö R.R|ë+H} Q ; ÆÆR, }ÇÊ.} S|} }ñ$Ê.}¤~Êx| Ö R.R|è(».ðx Ö R.R|:ìÓ9$; z 7ZRGLPHQVLRQDODUUD\ZLWKHOHPHQWVRIGLIIHUHQWOHQJWKV 1 2 3 4 5 6 7 8 9 10 11 12 } Ê|ÄÍ Ö R.RS|è(9 (9~ Û5S} (æÅ9A(+97; Êx|ÄÍ Ö RRxH|å(ã9~ .ÛH3} (+97; Êx|ÄÍ Ö RRxH|å(+.9~ .ÛH3} (æÄ397; Êx|ÄÍ Ö RRxH|å(æÄ9~ .ÛH3} (ÞÅ$97; ÆÆH.} Q v} Q v.SR }ÕxHÊx .Ñé } SHê$.HÊ7Î~¥Ê|ÄÍ Ö RR|ë+xS.} Q ; ÆÆ,ìí5Å ÆÆH.} Q v} Q P .Ó Ê$S x } SHê$.HÊ7.Î~¥Êx|ÄHÍ Ö RRxH|î(»93æx.} Q ; Æ Æ,ìí: } SHê$.HÊ7~¥Êx|ÄHÍ Ö RRxH|î(Þ$93æx.} Q ; Æ Æ,ìí,Ä } SHê$.HÊ7ÄÇ~¥Êx|ÄHÍ Ö RRxH|î(½Äo93æx.} Q ; Æ Æ,ìí5Å SAP AG 2004 The index of the last element of the array is not .length, but (.length -1). © SAP AG JA100 2-18 ([DPSOH7LF7DF7RH ; ; 1 2 3 4 7ZRGLPHQVLRQDO ILHOG [ER[HV HP Q .R Ñ( 9 (9~ xÛ xè(ã9À(æ9~óò½ðÝò; PSQ R (ÞÅ$9À(Å$9o; Hô(39 (Þ9~óò¯õîò; $Hå(æ39 (½Äo9~öòÓò ; xè(+9À(æ9~óòÓò; Hô(æ9 (Þ9~óò¾ðåò; $Hå(»9 (½Äo9~öòÓò ; xè(æÄ39À(æ9~óòÓò; Hô(ZÄ 9 (Þ9~óòÌò; $Hå(²Ä 9 (½Äo9~öò÷õîò ; PQ R Ý(9 (9~áààoø²ðçøSâvø²õßøHâvøÓø ä$âHà7øÓøHâvøðÝøâ,øÓø ä$âHà7øÓøHâvø,øâÓøõëøää; SAP AG 2006 © SAP AG JA100 2-19 *HQHUDO 9DULDEOHV'HFODUDWLRQ z 9DULDEOHLGHQWLILHUVVKRXOGEHZULWWHQLQORZHUFDVH ..} z 6HYHUDOGHFODUDWLRQVRIRQHW\SHEHRQWKHVDPHOLQHVHSDUDWHGE\ DFRPPD H} z 9 S..} Q â{Û.S} Q â Q Q }A; ,Q-DYDYDULDEOHQDPHVPXVWVWDUWZLWKDOHWWHUDQXQGHUVFRUH B RUDGROODU VLJQ .} z 9 Ï Q x~!ÄÅY¡¡H£; Ä¡êo} }; :RUGVUHVHUYHGE\-DYD NH\ZRUGV FDQQRWEHXVHGDVYDULDEOHQDPHV .} |}; SAP AG 2004 © SAP AG JA100 2-20 &RQVWDQWV z &RQVWDQWVDUHFUHDWHGE\XVLQJWKHNH\ZRUGILQDO z 7KHLGHQWLILHU QDPH RIDFRQVWDQWVKRXOGEHZULWWHQLQXSSHU FDVHRQO\ z 'HFODUDWLRQ HS <type> <NAME> = <value>; z ([DPSOH HS¤|$} Í Òù3ÒÐ Â ~:S ; SAP AG 2004 © SAP AG JA100 2-21 'DWD7\SHV6XPPDU\ <RXVKRXOGQRZEHDEOHWR z 'HVFULEHWKHEDVLF-DYDGDWDW\SHV z 'HFODUHYDULDEOHVDQGFRQVWDQWV z 'HILQHDQGXVHDUUD\V z &UHDWHDFODVV z ([SODLQWKHGLIIHUHQFHEHWZHHQ VLPSOHDQGUHIHUHQWLDOGDWDW\SHV z &RQYHUWGDWDW\SHV SAP AG 2004 © SAP AG JA100 2-22 ([SUHVVLRQVDQG6WDWHPHQWV &RQWHQWV z ,PSRUWDQWODQJXDJHHOHPHQWV z 2SHUDWRUV z %UDQFKHV z /RRSV SAP AG 2004 © SAP AG JA100 3-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z 'LVWLQJXLVKEHWZHHQDQGXVHGLIIHUHQWW\SHVRIRSHUDWRUV z 3URJUDPEUDQFKHV z 3URJUDPORRSV SAP AG 2004 © SAP AG JA100 3-2 ([SUHVVLRQVDQG6WDWHPHQWV 6WDWHPHQWV 9 6WDWHPHQWVDUHLQGLYLGXDORSHUDWLRQV WKDWDUHH[HFXWHGE\WKHFRPSLOHU 9 E\WH LM L M LL ([SUHVVLRQV 6WDWHPHQWH[HFXWHG &XUUHQWVWDWHPHQW 6WDWHPHQWQRW\HWSURFHVVHG ([SUHVVLRQVDUHVWDWHPHQWVWKDWUHWXUQ DUHVXOW E\WH LM 2EMHFW R L M LL R QHZ 2EMHFW SAP AG 2004 Statements y Embody an action y Are processed sequentially in a program y Possibly encapsulate further statements y Usually end with a semicolon Several statements can be on one line. Examples of statements: y Assignments y Declarations y Object creation y Loops y Branches y Error processing Expressions are elements of speech that incorporate values for variables. An expression can be: y A simple variable y A reference variable (object) y A literal y A value created by calculation or by a link © SAP AG JA100 3-3 /LWHUDOV z &RQVWDQWYDOXHVRIDSDUWLFXODU GDWDW\SHDUHFDOOHGOLWHUDOV z 7KHIROORZLQJOLWHUDOVH[LVW /RJLFDOOLWHUDOV WUXH ERROHDQ [ &KDUDFWHUOLWHUDOV FKDU F µ?Wµ )ORDWLQJSRLQWOLWHUDOV I IORDW I 6WULQJOLWHUDOV 5HIHUHQFHGDWDW\SHOLWHUDOV ³DVWULQJ³ 6WULQJV 2EMHFW REM ]HUR SAP AG 2004 Literals are expressions or parts of expressions. Variables are filled directly using literals. The following literals can be distinguished: y Logical literals The only literals are that are true and false. y Character literals These literals must always be enclosed in inverted commas. y Floating-point literals These are a number with a decimal point and/or an attached exponent and/or a suffix (f/F for float or d/D for double) according to the following schema: [Integer part][decimal point] [decimal places] [exponent][suffix] Example: 2.45f 123.45E-3 0.0123f 3D y String literals Strings are always specified in quotation marks. y Literals for reference data types In addition to the variables of simple data types, there are also reference variables that point to instances of classes. To determine that a reference variable does QRW point to any object, you can use the keyword ]HUR. © SAP AG JA100 3-4 2SHUDWRUV E\WH L 6WULQJVV V ³+HOOR ZRUOG³ V V³KRZ DUH \RX"³ L ([SUHVVLRQ 2SHUDWRU ([SUHVVLRQ ([SUHVVLRQ SAP AG 2004 Operators can generally link expressions to new, more complex expressions. Exception: Assignment operators (such as “=”) assign an expression to a variable. Operators are similar to mathematical functions: y They are supplied with arguments (for example, multiplicand and multiplier). y They supply a result. A fixed ranking exists for operators in which they are processed by the vm (for example, “point before stroke”). © SAP AG JA100 3-5 7\SHVRI2SHUDWRUV z 8QDU\RSHUDWRUV RQHDUJXPHQW z %LQDU\RSHUDWRUV WZRDUJXPHQWV z 7HUQDU\RSHUDWRUV WKUHHDUJXPHQWV SAP AG 2004 © SAP AG JA100 3-6 8QDU\2SHUDWRUV 7KH³´ RSHUDWRUGHOLYHUVWKHQHJDWLRQ RIDQDUELWUDU\%RROHDQYDULDEOH ERROHDQ GULYLQJ/LFHQVH WUXH ,I \RX GULYH ZLWKRXW DGULYLQJ OLFHQVH \RX DUH LVVXHG DZDUQLQJ ERROHDQ ZDUQLQJ GULYLQJ/LFHQVH SAP AG 2004 © SAP AG JA100 3-7 8QDU\2SHUDWRUV ,QFUHPHQWDQG'HFUHPHQW ,QFUHDVLQJDQGGHFUHDVLQJDQXPHULFYDULDEOHE\RQH LQW \ \ \ \LV \LV LQW \ LQW [ [ \ [ \ \LV [EXW RQO\ \LV [LV SAP AG 2004 The increment operator (++) increases a variable by one; the decrement operator (--) is reduced by one. x = y++; ( is x = y; y = y + 1; ) If the increment operator (the decrement operator) comes DIWHU the variables, the assignment is first carried out, and then the variable is increased (decreased). x = ++y; ( is y = y + 1; x = y; ) If the increment operator (the decrement operator) comes EHIRUH the variables, the variable is first increased (decreased) and then the assignment is carried out. © SAP AG JA100 3-8 %LQDU\2SHUDWRUV z $GGLWLRQVXEWUDFWLRQPXOWLSOLFDWLRQDQGGLYLVLRQ DUHSRVVLEOH \ [ [WKXV QRZ FRQWDLQV [ [ DQGQRZ [ [ $QGQRZ [ [ \ DQGQRZ z ,IIORDWLQJSRLQWQXPEHUVDUHDVVLJQHGWRLQWHJHUYDULDEOHV WKHGHFLPDOSODFHVDUHFXWRII LQW L LQW LFRQWDLQV QRW RU SAP AG 2004 © SAP AG JA100 3-9 %LQDU\ 2SHUDWRUV0RGXOR 2SHUDWRU 7KHPRGXORRSHUDWRU ³³ FDOFXODWHVWKHUHPDLQGHURID GLYLVLRQRSHUDWLRQ LQW UHVW E\LVUHPDLQGHU SAP AG 2004 © SAP AG JA100 3-10 %LQDU\ 2SHUDWRUV$VVLJQPHQW z $VVLJQPHQWRSHUDWRU ³ ³ ZLWKDQ DULWKPHWLFRSHUDWRU 2SHUDWRU 0HDQLQJ $GGLWLRQ ³³³³³ ³³³ DQGRWKHUV 6XEWUDFWLRQ 0XOWLSOLFDWLRQ 'LYLVLRQ 0RGXOR UHPDLQGHU LQW \ LQW [ \ \QRZFRQWDLQV [ \[QRZFRQWDLQV \ [\QRZFRQWDLQV \ [ QRZFRQWDLQV±DJDLQ SAP AG 2004 © SAP AG JA100 3-11 %LQDU\ 2SHUDWRUV5HODWLRQDO2SHUDWRUV 5HODWLRQDORSHUDWRUV DOZD\VUHWXUQD%RROHDQ WUXHRUIDOVH LQW NPK Operator == Meaning Equals != Not equal to < Less than <= Less than or equal to > Greater than >= Greater than or equal to ERROHDQ E ELVWUXH E NPK ELVIDOVH E NPK E NPK ! E NPK E NPK! E NPK ! ELVIDOVH ELVWUXH ELVWUXH ELVWUXH SAP AG 2004 © SAP AG JA100 3-12 %LQDU\2SHUDWRUV &RPSDULQJ6WULQJV ([DPSOH V Ù VDQGVSRLQWWRWKHVDPH PHPRU\ORFDWLRQV 0HPRU\ V V V VXSSOLHVWUXH VHTXDOV V VXSSOLHVWUXH DVWULQJ Ù 7KHVWULQJVUHIHUHQFHGE\VDQG VPDWFKRQHDQRWKHULQFRQWHQW DQRWKHUVWULQJ SAP AG 2004 Comparison via the = = operator tests whether both string variables reference the same object. Contrary to this, the comparison checks the equality of the content using equals (). © SAP AG JA100 3-13 %LQDU\ 2SHUDWRUV %RROHDQ 2SHUDWRUV z ,IRSHUDWRUVOLQNWZR%RROHDQH[SUHVVLRQVZLWKRQHDQRWKHU LWZLOOUHWXUQD%RROHDQYDOXH _ A z ORJLFDO$1' ORJLFDO25 H[FOXVLYH25 2SHUDWRUVZLWKVKRUWHYDOXDWLRQ ,IWKHOHIWKDQGRSHUDQGDOUHDG\GHWHUPLQHVWKHUHVXOWRIWKH RYHUDOOH[SUHVVLRQWKHULJKWKDQGRQHLVQRORQJHUHYDOXDWHG __ ORJLFDO$1' ORJLFDO25 SAP AG 2004 © SAP AG JA100 3-14 %LQDU\2SHUDWRUV %RROHDQ2SHUDWRUV LQW NPK IORDW SHU0LOO I ERROHDQ GULYLQJ/LFHQVHZDUQLQJ 'ULYLQJOLFHQVHLVQRWFRQILVFDWHGLIVSHHG OHVVWKDQRUHTXDOWRNPKDQGOHVVWKDQSHU0LOO GULYLQJ/LFHQVH NPK SHU0LOO :DUQLQJIRUVSHHGVRYHUNPKRUPRUHWKDQ SHU0LOO ZDUQLQJ NPK ! __ SHU0LOO ! SAP AG 2004 © SAP AG JA100 3-15 %LQDU\ 2SHUDWRUV &RQFDWHQDWLRQRIVWULQJV 9DULDEOHVDQGOLWHUDOVRIW\SHV6WULQJDQGFKDU FDQEHOLQNHGWRD6WULQJXVLQJWKHRSHUDWRU³´ 6WULQJV ³ PRUH³ 6WULQJD ³ QRWKLQJ OHVV³ FKDU F µµ 6WULQJ[ ³1RWKLQJ³ VDF LQW LG[ 6WULQJDEF ³7KH DQVZHU LV³ LG[ SAP AG 2004 Character chains, which are saved in the virtual machine in string objects, have the property that their content can no longer be changed. After initialization of a string, its length and content remain constant. This means that, for example, when using the + operator, a completely new string object is created from the strings to be linked and this is supplied as a result. However, sometimes it is useful to have character chains that can be changed dynamically. For this purpose, Java has the StringBuffer class. This works similarly to string, but implements character chains on which changes can be made. © SAP AG JA100 3-16 7HUQDU\2SHUDWRUV &RQGLWLRQDO6WDWHPHQW z 6\QWD[GLDJUDP ERROHDQ H[SUHVVLRQ!"WUXH!IDOVH! z ([DPSOH ! ! $#% " !$& (') * ,+.-/ 00213 ! %//2 24!"" 657 24/ 00 ')9 5:;<24!" (+-=9 !8#82 84!" SAP AG 2004 The conditional statement is a short form of the if statement. © SAP AG JA100 3-17 ,I 6WDWHPHQW z 6\QWD[GLDJUDP $IWHULIHOVH \RXKDYH HLWKHU 3?>A@(BDCCEFGHFIJLKFMMN CH OPRQ S SUT KVF W ! Q [ SS$X GE MF W z ([DFWO\RQH VWDWHPHQW z $ VWDWHPHQWEORFN ^` ] z ([DPSOH 3 W > Y/[ZR\ PRQ ] ^ "%U_a`b_c 3 0 0ed /gf/ h\ Y 00 /$.[ci ] ^". W /! Q ] ^ "%U_j k.fl`m "/6`on ! > kqpr P SAP AG 2004 After LI or HOVH, there is either exactly one statement or a statement block. This is introduced and closed by curly brackets. Any number of statements are contained within the brackets and these end with a semicolon, as usual. © SAP AG JA100 3-18 7KH1HVWHGLI6WDWHPHQW z 6\QWD[GLDJUDP 3s>t@(BDCCEFGHuFIJLKFMMNCHvO$PUQ SShT K/VF$v W /!g 3?> [ SSUT K VF2x W [ ] /!( < BCCEFGH<FIwJaK FMMNCHyx > PQ Q SS$X GEMFgx W ] z ([DPSOH z{ |~}z( 7g zwe[{L 77%,$}zzz wz{ |¡}z( t% [ zwe[¢{L 7£¤¥}z ¦§ze¢z(( w t¨,w© z(eª¤L| zwe[. «b¬ w(­®D°¯ z(/(6| ± « ¬6² ± SAP AG 2004 If the <boolean expression 1> returns the value “ true,” then the statement block “ true 1” is executed. If it returns the value “ false,” then the second if query is processed. If the <boolean expression 2>true is supplied, then the statement block “ true 2” is executed. If false is supplied, then the statement block “ false 2” is executed. © SAP AG JA100 3-19 7KH6ZLWFK6WDWHPHQW z 6\QWD[GLDJUDP VZLWFK <expression> ^ FDVH <constant>: <statement> ... >EUHDN@ [FDVH < constant >: < statement > ... >EUHDN@ ] [GHIDXOW: < statement > ... >EUHDN@ ] ` SAP AG 2004 The switch statement is a multiple branch. First, the expression given behind switch, which must be of the type byte, short, char or int, is evaluated. Depending on the result, the jump label, whose constant corresponds to the result of the expression, is then activated. The constants and the expression must be assignment-compatible. The optional default label is then activated if no suitable jump label is found. If no default label exists and no suitable jump label is found, none of the statements is executed within the switch statement. Every constant of a case label can only occur once. The default label can only be used once. After a case or default label is activated, all subsequent statements are executed. A disruption does not take place when the next label has been reached. If this is desired, the control flow must be interrupted using a break statement. Every break within a switch statement causes the switch statement to be branched at the end. © SAP AG JA100 3-20 &RPPDQG6HTXHQFHIRUVZLWFK z ([DPSOH ZLWKRXWEUHDN VWDWHPHQW 323 = 323 ´ (; 323 3 ` `` w;/^ >o3PRQ ^ L* ^ ´j* ] 3 "/! * ^ ­* W kfl`m "­`onD! kfl`m "­`onD! kfl`m "­`onD! kfl`m "­`onD! > ³ ^< ³ P > ³ ^$´ ³ P > ³ ] 3 "! ³ P > ³ ^2 ³ P z ([DPSOH ZLWKEUHDNVWDWHPHQW 3$3 = 3$3 ´ / ; 3$3 3 ``` (;^ >o3/P Q ^ L*µkf¶`r"/·`°nD ! Y ^ ´j*µkf¶`r"/·`°nD ! Y ] 3 "! *tkf¶`r"/·`°nD ! Y ^ ­*µkf¶`r"/·`°nD ! Y W > ³ ^R ³ P > ³ ^´ ³ P > ³ ] 3 "! ³ P > ³ ^u ³ P SAP AG 2004 The case (or default) statements act as markers. If the query expression that is behind switch assumes a value mentioned in a case statement, this case statement is processed and the statements there are executed. If the query expression assumes a value that has not been entered via a case statement, then the default statement is activated. If this does not exist, the switch statement ends and is continued with the first statement after the switch block. The default statement need not be implemented at the end of the switch block. © SAP AG JA100 3-21 /RRSV7KUHH%DVLF7\SHV z 6\QWD[GLDJUDP ZKLOH/RRS >t@(BDCCEFGHuFIJLKFMM NCH/O[PDQ ; ! ¸¸¸ W z 6\QWD[GLDJUDP GRZKLOH/RRS ] Q W ;! ¸¸ ¸ >:@(BC CEFGH<FIJ=KFMMNCH O$P z 6\QWD[GLDJUDP IRU/RRS 3 >A@N HN T O @B.CCEFGH<FI(JaKFMMNCHO @/V¹JLºG T FOPRQ W ¸¸¸ SAP AG 2004 while loops (header-controlled loops) The loop is run through if the Boolean expression returns the value true. do while loops (footer-controlled loops) The loop is run through at least once. If the Boolean expression returns the value true after the loop is run through, then the loop is run through again. for loop (count loop) y The LQLWLDOL]DWLRQSDUWcontains a series of declaration and assignment statements separated by commas, and has a semicolon at the end. These declarations are only valid for the area of the for statement and its sub-statements. The assignments are only carried out once before the first execution of the sub-statements. y The WHVWSDUW contains a boolean expression that is re-evaluated once per loop run. If the expression “ false” is delivered, the control goes to the next statement after the for statement and its sub-statements. This part ends with a semicolon. y The LQFUHPHQWSDUW contains a series of expressions separated by commas, which are evaluated once per loop run. This part is generally used to increase an index that is checked in the test part. © SAP AG JA100 3-22 ,PSOHPHQWDWLRQRIWKHIRU/RRS / 3 3 >o3 U_= 3 ÄÇÁ¼ 3 ¾¾ PRQ k.f¶`m"6`ÈnD ! > (4/ !"$ 383 *7 ¾ 3.P W 00 3s> /%4 !"<_ P 8Á[ 3 2!4 u!(n z IRUORRSZLWKLQLWLDOL]DWLRQRIVHYHUDOYDULDEOHV 3 > [»¼5½¾ R¿=5:YRÀwRÁae½§¾8Y8Z8Ât½ÀÀ PRQ 00 ] <f/ W z IRUORRSZLWKQHZORFDOYDULDEOH 3 > f<U_LÃf2ÄÅ_aÃf/¾¾ PUQ 00 ] <f/. W z IRUORRSZLWKVHYHUDOPRGLILHGYDULDEOHV 3 > [R_a5e½ÆR_=2Z½LÀÀ=5e½¾¾ PRQ 00 ] <f. W SAP AG 2004 © SAP AG JA100 3-23 7KHEUHDN6WDWHPHQW:LWKLQ/RRSV z EUHDN 3 h__L ;! > " P Q 3 >m3 ÄU_ PRQ Y W ! Q 3 ÀÀj W 00 ] f.(. W 00 ;! z FRQWLQXH 3 U__L ;! > " P Q 3 >m3 ÄU_ PUQ 00 `` ` ^. " W ! Q 3 ÀÀj W 00 ] f/.(. W 00 ;! SAP AG 2004 The execution of a loop can be interrupted by the break statement. After the break statement, the program is continued with the first statement after the loop. The execution of a loop can be manipulated by the continue statement. With the continue statement, the current loop run is terminated and started in a new loop run. © SAP AG JA100 3-24 8VLQJEUHDNFRQWLQXHZLWK/DEHOV z )RUQHVWHGORRSV\RXFDQGHILQHODEHOV z 7KHVWDWHPHQWEUHDNODEHO!WKHQOHDYHVWKHORRSWKDW ZDVQDPHGYLDWKHODEHO ÊÉA˼É,Ë ] [Ì` `` ^ ] )k$Ì``` 1 /^ .(ͼÎa* 3 > ½ÆR_=e½Ä 3 3 W W ] l`!.le½¾¾ P Q > . YgR_=tY%Ä ] .lÉr½/Ë=`! l:Y¾¾ P Q > ] lÉr½Ë­ÉÈY=Ë=`ÏÐ"/!. > ^ ] ) .k PPRQ kf¶`r"D¼`onD ! > ('(nn6pppp, P Y 1 ^.Í=έ W SAP AG 2004 If several loops are nested in one another, individual loops can be described via prefixed labels. A call of break or continue with an attached label causes a leaving or continued counting of the loop described by the label. © SAP AG JA100 3-25 6XPPDU\RIWKH6\QWD[ $VDUXOHWKHVHPLFRORQ³´ LVSODFHGDIWHUDVWDWHPHQW $IWHUEUDQFKHV LIVZLWFK RUORRSV ZKLOHGR DQGIRU WKHUHLVQRVHPLFRORQ,QVWHDGWKHUHLVDVLQJOHVWDWHPHQWRUD EORFNRIVWDWHPHQWVWKDWEHJLQVDQGHQGVZLWKFXUO\EUDFNHWV $IWHUDODEHODVZHOODVDIWHUFDVH WKHUHLVDFRORQ³´ SAP AG 2004 © SAP AG JA100 3-26 ([SUHVVLRQVDQG6WDWHPHQWV 6XPPDU\ <RXVKRXOGQRZEH DEOHWR z 'LVWLQJXLVKEHWZHHQDQGXVHGLIIHUHQWW\SHVRIRSHUDWRUV z 3URJUDPEUDQFKHV z 3URJUDPORRSV SAP AG 2004 © SAP AG JA100 3-27 © SAP AG JA100 3-28 ([HUFLVH 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF 2SHUDWRUV At the conclusion of this exercise, you will be able to: • Use individual operators • Create a class using the development environment 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 1-1 6WDUW8S.LW FRPVDSWUDLQLQJVRO Open the 6WDUW8S.LW project in the development environment. In this project, switch to the FRPVDSWUDLQLQJH[F package. There you will find a file with the name 2SHUDWRUVW[W. Open this file using the development environment. One of your colleagues (C programmer) has sent you this programming code. Try to understand the statements. What are the values of x, y, z, and the rest of the variables? 1-2 In the FRPVDSWUDLQLQJH[F package, define a new class with the name 2SHUDWRUV in a file named accordingly. When creating the class, use the wizard to generate a main method. With the help of this class, you should check your considerations from step 1-1. 1-3 Use the cut and paste functions to copy the statements from the text file to the main method. 1-4 Save the class and execute the program. © SAP AG JA100 3-29 © SAP AG JA100 3-30 6ROXWLRQ 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF 2SHUDWRUV 1-1 What are the values of x, y, z, and the rest of the variables? &DXWLRQ$YRLGSURJUDPPLQJOLNHWKLV LQW[\ ] UHVW ] [ \ UHVW ] ] [ \ First, the y value is incremented (y = 21) Then, x is assigned (x = 61) Afterwards, values are multiplied (z = z * x -> z = 183) UHVW ] Rest is the remainder of the integer division of 183 divided by 5, thus 3. © SAP AG JA100 3-31 © SAP AG JA100 3-32 ([HUFLVH 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF 2SHUDWRUV At the conclusion of this exercise, you will be able to: • Compare string values • Link conditions with AND and OR • Negate conditions 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJVRO 2-1 Change to the FRPVDSWUDLQLQJH[Fpackage. Here, you will find the &DU&KRRVHclass. 2-2 Replace the comment line ³WREHUHSODFHG!´with the following program code: First, define the following variables: 7\SH 1DPH LQW NP&RXQW ERROHDQ OHQW 6WULQJ YDOXH )UHHFKRLFH PRGHO ERROHDQ )UHHFKRLFH IDOVH FKRRVH7KLV&DU IDOVH (Note: Initilaize the variables according to the value column.) 2-3 Find out whether a car has been selected by a customer because it has the properties he wants. Create the following compound condition and assign the result to the FKRRVH7KLV&DU variable: • The model is a “ BMW” and the mileage is below 100,000 The model equals RSWLRQDO&DU (this variable is already defined) and the mileage is below RSW.P&RXQW(this variable is also defined). In any case, the car must not be rented. • © SAP AG JA100 3-33 2-4 Remove the comment block in the program that is placed around the output statements. Compile and test the program. Repeat the test several times and vary the values for the variables PRGHO, NP&RXQW, and OHQW. Check whether or not the condition returns a correct result. © SAP AG JA100 3-34 6ROXWLRQ 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF 2SHUDWRUV SXEOLF FODVV CarChoose { SXEOLF VWDWLF YRLG main(java.lang.String[] args) { String optionalCar = "VW"; LQW optKmCount = 30000; String model = "BMW"; LQW kmCount = 80000; ERROHDQ lent = IDOVH; ERROHDQ chooseThisCar = IDOVH; chooseThisCar = (((model.equals("BMW") && (kmCount < 100000)) || (model.equals(optionalCar) && (kmCount <= optKmCount))) && !lent); System.out.println(); System.out.println("model: " + model); System.out.println("km " + kmCount); System.out.println("lent: " + lent); System.out.println(); System.out.println("condition: " + chooseThisCar); } } © SAP AG JA100 3-35 © SAP AG JA100 3-36 ([HUFLVH 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF ,IVWDWHPHQW At the conclusion of this exercise, you will be able to: • Program a complex if statement • Use the ternary operator 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 3-1 FRPVDSWUDLQLQJVRO Stay in the FRPVDSWUDLQLQJH[Fpackage. There you will find the ,I&ODXVHclass, which you should use to calculate the tax category of a car. Two variables have already been declared: SV FDWHJRU\ 3-2 6WDUW8S.LW Contains the car performance in horsepower (hp) Will contain the tax category Replace the comment line “ // WREHUHSODFHG!” with the following coding.Implement a further ifstatement through which the FDWHJRU\ variable should be filled. • If the hp number is smaller than 70, FDWHJRU\ should equal 1. • If the hp number is greater than or equal to 70, but less than 100, the FDWHJRU\ should be equal to 2. • If the hp number is greater than or equal to 100, but less than 150, the FDWHJRU\ should be equal to 3. • Otherwise, FDWHJRU\ should be 4. Enclose your statements within an LIor HOVHbranch in curly brackets. 3-3 Declare a string variable and call it NLQG2I&DU. 3-4 Allocate this variable the following value using the ternary operator: 3-5 ³3RZHU&DU´, if FDWHJRU\ is greater than 2, otherwise ³1RUPDO&DU´. Remove the comment now in the output statements in the class. Compile the class and execute it. Use different hp numbers and repeat the run. © SAP AG JA100 3-37 © SAP AG JA100 3-38 6ROXWLRQ 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF ,IVWDWHPHQW SXEOLF FODVV IfClause { SXEOLF VWDWLF YRLG main(java.lang.String[] args) { -{}LQW ps = 110; LQW category; String kindOfCar; LI (ps < 70) { category = 1; } HOVH LI (ps < 100) { category = 2; } HOVH LI (ps < 150) { category = 3; } HOVH { category = 4; } kindOfCar = (category > 2) ? "PowerCar" : "NormalCar"; System.out.println("ps: System.out.println("category: System.out.println("kindOfCar: " + ps); " + category); " + kindOfCar); } } © SAP AG JA100 3-39 © SAP AG JA100 3-40 ([HUFLVH 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF 7KH6ZLWFK6WDWHPHQW At the conclusion of this exercise, you will be able to: • Program a switch statement • Use the break statement 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 4-1 FRPVDSWUDLQLQJVRO Stay in the FRPVDSWUDLQLQJH[Fpackage. There you will find the 6ZLWFK&ODXVH class with which the annual tax rate of a car should be calculated. Two variables have already been declared: FDWHJRU\ WD[ 4-2 6WDUW8S.LW contains the tax category (that does not have to be calculated any more in this exercise), will contain the tax rates in EUR. Replace the comment line “ // WREHUHSODFHG!” with the following program logic. Implement a VZLWFK branch that examines the value of the expression FDWHJRU\±: • If the value is 0, the tax rate should be EUR 250 • If the value is 1, the tax rate should be EUR 320 • If the value is 2, the tax rate should be EUR 400 • In all other cases, the tax rate should be EUR 500 First, implement the switchstatement without using break. Compile the class and execute the program. What values are output? Why do you receive a tax rate of EUR 500, although only EUR 320 should actually be paid for tax rate 2 specified in the class? 4-3 Insert the EUHDN statement at the correct position. Compile and test the class again. © SAP AG JA100 3-41 4-4 Due to changes in tax policies, categories 2 and 3 are now combined and both have the same rate of EUR 290. Change the VZLWFK statement so that there are only three WD[ statements in the whole statement. Compile and test the class again. © SAP AG JA100 3-42 6ROXWLRQ 8QLW ([SUHVVLRQVDQG6WDWHPHQWV 7RSLF 7KHVZLWFK6WDWHPHQW 4-2 //... SXEOLF VWDWLF YRLG main(String[] args) { //... VZLWFK (category - 1) { FDVH 0 : tax = 250; FDVH 1 : tax = 320; FDVH 2 : tax = 400; GHIDXOW : tax = 500; } //... } //... 4-3 //... SXEOLF VWDWLF YRLG main(String[] args) { //... VZLWFK (category - 1) { FDVH 0 : tax = 250; EUHDN; FDVH 1 : tax = 320; EUHDN; FDVH 2 : tax = 400; EUHDN; GHIDXOW : tax = 500; EUHDN; } //... } //... © SAP AG JA100 3-43 4-4 //... SXEOLF VWDWLF YRLG main(String[] args) { //... VZLWFK (category - 1) { FDVH 0 : tax = 250; EUHDN; FDVH 1 : FDVH 2 : tax = 290; EUHDN; GHIDXOW : tax = 500; EUHDN; } //... } //... © SAP AG JA100 3-44 2EMHFW2ULHQWHG 3URJUDPPLQJ &RQWHQWV z &ODVVHV z $WWULEXWHVDQGPHWKRGV z &UHDWLQJ REMHFWV z 5HOHDVLQJ REMHFWV SAP AG 2004 © SAP AG JA100 4-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z 'HILQH FODVVHV z &UHDWHDWWULEXWHVDQGPHWKRGVLQFODVVHV z $SSURSULDWHO\LPSOHPHQWYLVLELOLW\DUHDVIRUDWWULEXWHV DQGPHWKRGV z &UHDWHLQVWDQFHVRIFODVVHVDQGUHUHOHDVH WKHP z &DOO XSPHWKRGV z 8VH FRQVWUXFWRUV SAP AG 2004 © SAP AG JA100 4-2 &ODVVHV 9HKLFOH &ODVV QDPH SAP AG 2004 A class is a data structure containing attributes and functions. As a reference type, it represents a blueprint from which any number of instances (or objects) can be created. Objects consist of object data (properties, attributes) and the algorithms (object methods) with which the objects realize their functionality. All the objects in a class have the same attributes, but with different attribute values. © SAP AG JA100 4-3 &ODVVHV DQG$WWULEXWHV 'HILQH WKH DWWULEXWHV >PRGLILHU!@W\SH!DWWULEXWHQDPH! Vehicle !#"$!% & '#() (* &+() ,-/. $WWULEXWHV SAP AG 2004 A class attribute is part of the class definition and can be a variable of a simple data type, an array, or an object (reference data type). The attribute values of an object determine its state during runtime. Attributes apply for all methods of the object. Within methods, variables can be created, which are then only visible within these methods. © SAP AG JA100 4-4 &ODVVHV$WWULEXWHVDQG0HWKRGV 'HILQLQJ PHWKRGV >PRGLILHU!@UHWXUQW\SH!PHWKRGQDPH! >SDUDPHWHUOLVW!@ ^«` # # 6 # "$@% Vehicle "AB #@# C#D @FEHGI @ "@ J "ABK!L #D@ !MEN OD@@GP KQ D R - color - volume 021 .3546() (*5798 0;: .3546() (*5798 021 .3=<>()?,-/.798 0;: .3=<>()?,-/.7=8 "AB O !S@#"$@FEHGP @ "@ " $R "ABK!L T@"$@UE @ V@L@JW @ L # GI !" $XQCVLPYZ!! [ Y L B R #!6W SAP AG 2004 A method combines one or more statements into a logical unit. Methode define the behavior of objects and can be called up by using transfer parameters. © SAP AG JA100 4-5 &ODVVHV$WWULEXWHVDQG0HWKRGV 5HWXUQYDOXH RIPHWKRGV UHWXUQ YDOXH! @\ > !6 ]@]] "AB @# C#D! @MEHGI @ " R z z 7KHUHWXUQVWDWHPHQWOHDGVWRWHUPLQDWLRQRIWKHPHWKRG 7KHYDOXHRIWKHVSHFLILHGH[SUHVVLRQLVUHWXUQHGWRWKHFDOOHU SAP AG 2004 The return value of a method can be a primitive type, an object type, or void. Methods can return a value to the caller using the return statement. You can also use the return statement to branch out of the loop statement. © SAP AG JA100 4-6 &ODVVHV$WWULEXWHVDQG0HWKRGV 2YHUORDGLQJ PHWKRGV ]]@] "A! K@#L !^@#"UE ! ]]@] _W @ A`W "A! K@#L ]]@] !^@#"UE ! _W @ A6GI "A! K@#L ]]@] !^@#"UE ! _W b@@ bG Ga B c@ P "#AB@C# K L $!@#dEN O@JegfGP !@ h$!i# jQ V @ 2EkG $ iB ] ^ lB"2Enm#o!p>Wqo@prWsm p@ptG> $ iB ] ^ lB"2Evup@ppWsmppGB SAP AG 2004 In Java, methods with identical names can be defined within a class, as long as they differ in terms of the number or type of parameters (or both). The purpose of this is to pass parameters with different data types to operations with semantically similar, identically-named operations or, in the case of constructors, to offer the correct instantiation behavior for input data with different data structures. © SAP AG JA100 4-7 9DUDUJV $UJXPHQWOLVWVRI YDULDEOHOHQJWK • A formal parameter stands for any number of actual arguments. • Declaration by adding three periods to the type name of the parameter. • They are accessed in the same way as arrays. -6( SAP AG 2006 Up to and including J2SE 1.4.2, to allow a variable number of parameters for a method, you must program the same method multiple times with a different number of arguments each time. Alternatively, you can pack all arguments into a dynamic container (See "Collection Framework") and then transfer this container to the function. As of J2SE 5.0, you can add three periods to a type in the method signature, so that it can contain argument lists of variable lengths. The three periods indicate that at this point, when called, any number of arguments of the relevant type may be transferred. Alternatively, an array of the relevant type can be transferred. Technically, this declaration corresponds to that of an array parameter. That is to say, the runtime system automatically generates an array in which the submitted values are transmitted. Access to the values is as follows: ’length’ indicates the number of arguments and square brackets indicate the individual arguments with indexing . In addition to the variable parameter lists, additional arguments may also appear in the method signature. The varargs must always appear last. To access varargs, you can also use the enhanced for loop which has been introduced as of J2SE 5.0 (for more information about the foreach loop, see "Collection Framework"). © SAP AG JA100 4-8 &ODVVHV$WWULEXWHV0HWKRGVDQG,QVWDQFHV &UHDWH LQVWDQFHV 9HKLFOH - color - volume &ODVVQDPH!REMHFWQDPH! QHZ &ODVVQDPH! @c!w "A x K!L $ yEz 2elf{@ @@GI + getColor() + setColor() + getVolume() + setVolume() #h$ i! mr $ i# @#mZQ V FE|G> #h$ i! V uKQ ! /EnGr |~S S ~ '#(!- : 3n* @?1 .-( <B. ') .# g# H~^ ~T '#(@- : 3z* ? ?1 .-(! < . ') .###^# }>~gr# SAP AG 2004 An instance is described by a class. That is, a class forms the template according to which one or more instances are created. A class represents a reference data type with which objects can be created. You can tell the difference between instances (objects) of a class by the different values of their attributes. An object has a life cycle; that is, it must be created once within a program, is active, can change its state during its existence and – as soon as it is no longer needed – is destroyed. Objects have a state and an identity with which they can be distinguished from other objects of the same class. © SAP AG JA100 4-9 (QFDSVXODWLRQ (QFDSVXODWLRQ @ B @6 B @#"$!J "A> #@j D@ !%EHGI " R "A> X!L ^#D @%ENOD@Gx ¡Q D@R "A> ¡@ @ ^@ "#$FE|Ga " !"$J "A> X!L ^TB#"$ UE ! V L JW ! # L^Ga "#$!jQjV#LwYZ#!Y[L _ #¢W SAP AG 2004 The idea behind encapsulation is that you cannot access attributes of a class directly from the outside, but only via get/set methods. The developer can hide attributes and methods of the class from the outside by using a modifier. This means that attributes of an object can only be manipulated using their associated methods, and that methods themselves are protected (or encapsulated) from unauthorized access. © SAP AG JA100 4-10 $FFHVVWR3XEOLF,QVWDQFH&RPSRQHQWV &DOOLQJXSSXEOLF LQVWDQFHPHWKRGV REMHFWQDPH!PHWKRG! SDUDPHWHUOLVW! @c!w "AB O## K@L $@@ yEn#@# ¢eSfGI @ $ i jQ V ;EHG> $i # ] #D 2E £NAB#"@>£ GB $FFHVVWRSXEOLF LQVWDQFHDWWULEXWHV REMHFWQDPH!DWWULEXWH! @ c!w !" AB j #! K@ L $@@ yEn @# O¢eSfGI X$ i! jQ V ! ;EHG $!i# @ ] @@[Q £¤A"6£ SAP AG 2004 Object attributes can be accessed either directly (using period notation) or (ideally) using special access methods (encapsulation.). Attributes defined as private can, for example, be read and changed via methods defined as public. Advantages: y “Getter/Setter” methods are necessary for standardizing (JavaBeans). y A manipulation of the objects by directly changing their attribute values is prevented, and erroneous states can be avoided by checks in the respective methods. y By using methods, the implementation of the class remains hidden to the user. Thus the class designer can change or extend the class later, but these changes will not be visible from outside the class. © SAP AG JA100 4-11 7KLV 5HIHUHQFH Vehicle &'() (* &+ () ,-/. 0;: .3v4() (*57=8 0;: .39< (),-U. 798 @ ! ! ¢ # @#"$@% "#AB KL #D FEkO@@@GI @ ] KQ¢ "#AB KL TB"$!2E @ V#L! RW @ ! !¢W @ L B GI @ ] " $CQCV L PYZ@ Y[L ^_ SAP AG 2004 “This” is a pointer that is generated automatically when you create an object. It is a reference variable that points to the current object and can be used to address the instance methods and instance attributes of this object. The this pointer can be used like a normal object variable. An instance method can generally be accessed directly on the instance attribute of its class without using the this pointer. However, sometimes it makes sense to use this, even when it is not absolutely necessary. This makes it clear that you are you are accessing an instance attribute. © SAP AG JA100 4-12 &RQVWUXFWRU z z z 6SHFLDOPHWKRGIRULQLWLDOL]LQJREMHFWV %HDUVWKHVDPHQDPHDVWKHFODVV &DQRQO\EHFDOOHGXVLQJWKHQHZ RSHUDWRU #!@ R "A ! `En @KQ D @6 &RQVWUXFWRU D @!GI "A C #D `EkGa " @ ¢ @ c!w "#AB ¡@ L $@ yEn O!%e|f#GI ! @ h$!i# ¡Q V B dE ¥A!" ¥ G6 ¦¦ j@O A" ^i>$ ] " ] @#/E§$!i# @ ] #D! @MEHGG6 SAP AG 2004 Constructors are special methods that can be called to initialize an object. Constructors in Java: y Have the same name as their class y Do not return a value y Can have any number of parameters y Can be overloaded If you want to initialize relatively complex static variables (that is, class variables), you can define static initializing blocks (sometimes known as “static constructors”). These are called up only once during the program run when the class is loaded. © SAP AG JA100 4-13 2YHUORDGLQJ &RQVWUXFWRUV &'() (!* &+ () ,-U. 9HKLFOH 0 < . ') .7='#() (*z¨ ©@3k* ?1 8 0 < . ') .7='#() (*z¨ ©@3k* ?1@ª +()?,-/. ¨ ? 358 \ ! !O @#"$ M " AB @! /E« #@ G ] KQ " AB @! /E« #@ _W @ !"#$@BGI Ez G> ] " $jQC!#"#$J SAP AG 2004 © SAP AG JA100 4-14 6WDWLF$WWULEXWHVDQG0HWKRGV 6WDWLF$WWULEXWHVDQG0HWKRGV VWDWLF z Static attributes and methods exist independent of an instance of a class. z You can access it without using an instance of this class. z All instances of a class access the same attribute or method. $FFHVVLQJ3XEOLF6WDWLF$WWULEXWHVDQG0HWKRGV FODVVQDPHDWWULEXWH! RU FODVVQDPHPHWKRG! ¬­#®¯#¯ ° ±²³¬ ­±O´ µ¶ ³S·®¸^±K¯ ¸^®¸³#¬[³^¹¸ ¹gº@»Sº· ±²³#¬­±¯¼ µ½¾ ­³#¬ °!±²³¬#­±J¿|À´ ¹gº »lº·±#²³#¬­±¯^ÁÁ¼   µ½¾ ­³#¬[¯¸®¸^³#¬{³#¹¸ à ±¸¤Ä º@»¤º·±²@³#¬#­^±¯r¿nÀ¡´ ¶±¸T½¶¹ ¹gº »lº·± ²³#¬­±¯ ¼  ¬#­®¯#¯ °±²³¬#­± ű¯ ¸C´ µ½¾ ­ ³¬Z¯¸^®¸^³#¬q·» ³Æ Ç® ³#¹R¿«È¸^¶³¹ ÃJÉ|ÊË®#¶Ã¯À[´ ³^¹ ¸ ¬»#½ ¹¸S±#¶sÌ °±²³ ¬­±Í5Ã#±¸¤Ä º@»lº·±² ³#¬ ­±¯r¿nÀ ¼   SAP AG 2006 Java is a logically consistent object-oriented language that does not permit global data or global functions. However, the static modifier allows you to declare attributes and methods that are not bound to an instance of a class. These exist from the time the class is loaded until the program ends. Attributes within the class that are declared VWDWLF, exist independently of any object. These class variables are created once only and can be accessed by all the methods of that class. This means that changes made to a class variable by one of the instances of the class are visible to all its other instances. Class methods exist independently of specific instances of a class. Class methods point to classes, which means that they cannot change objects themselves. Like class variables, class methods affect the whole class, not just individual instances of it. Class methods are normally used for general utility methods, which are not intended for use directly on an instance of the class, but belong conceptually in this class. © SAP AG JA100 4-15 6WDWLF,PSRUWV 6WDWLF,PSRUWV • Unqualified access to static components of a class or an interface using the special import statement "import static". -6( SAP AG 2006 In Java, each method always belongs to a class. As a result, in the case of static methods, the class in which the static method is located is always required for a function call. Up until J2SE 1.4.2, the relevant type name is always inserted as a prefix when calling a static method and when accessing a static attribute. The syntax for calling the static method sin() from the java.lang.Math class, is therefore Math.sin(...). Correspondingly, the static attribute PI from class Math is addressed using Math.PI. As of J2SE 5.0, you have the option of using static parts of classes and interfaces without prefixing the class name or interface name. The required components are enumerated using the special import statement "import static". The imported components can then be accessed unqualified. These static imports can be used to import individual static methods and attributes (for example, import static java.lang.Math.sin;) or, if you enter "*", you can import all static components of a class or an interface (for example, import static java.lang.Math.*;). © SAP AG JA100 4-16 $FFHVV2SWLRQVIRU0HWKRGV z ,QVWDQFHPHWKRGVFDQDFFHVV LQVWDQFHFRPSRQHQWVDQG VWDWLFFRPSRQHQWV ÎÎÏ#Ð!Ñ ÒhÓXÔ!ÕÖ ×¢Ø@ØØ Ø ÙÚ ÓÑÑ Ô!Õ#Ö!×\Û ÜBÝÞß ÓÒ#ÕaÑÒÓÒ ÞÙOÞà Ò Ù ×Ð à Ò#Õ Ýá ÜBÝÞß ÓÒ#Õ âÒ ÝÞàã Ó!ÒÒ ÝRá z 6WDWLFPHWKRGVFDQRQO\ DFFHVVVWDWLF FRPSRQHQWV SAP AG 2006 © SAP AG í Ü Ðä ÚÞ ÙXß × Þå Ñ^ÕÒgæ Ó Ú Ð@ÕFçNâÒ ÝÞàã ÓSæ>Ó Ú ÐÕBèÛ ÓÒÒ ÝXé Ó#æ!Ó Ú Ð@Õ á ÞàÙ Ý ÕÓÑÕ@ê×Ð à Ò#Õ Ý çkè á â ëÑÒ#ÕÖ2ìk×Ð@ÒRì ÜBÝÞà Ò Úà ç Ù ×Ð à ÒÕ Ý è á Ü>ÝÞà ÒTæBÓ Ú ÐÕUçzè á í Ü Ðä ÚÞ ÙXß × Þå Ü!Ý Þà ÒgæÓ Ú Ð!ÕFçHèPÛ ì@ìì í Ü Ðä ÚÞ Ù ÑÒ#ÓÒ Þ@Ùhß × Þå Þ#àÙÝ ÕÓÑÕê ×#Ð à Ò Õ Ý çkèIÛ Ù ×#Ð à ÒÕ Ýî îá Ó à ×ÒïÕ Ý â ÒÓÒ Þ Ù^ð Õ!Òï!× å çkè á Ü>ÝÞà ÒTæBÓ Ú ÐÕUçzè á â ëÑÒ#ÕÖ2ìk×Ð@ÒRì ÜBÝÞà Ò Úà çzÓ ÒÒ Ý è á í Ü Ðä ÚÞ Ù ÑÒ#ÓÒ Þ@Ùhß × Þå Ó à ×Ò ïÕ Ý âÒÓÒ ÞÙð ÕÒï× å ç|èÛ ì@ìì í JA100 4-17 0DLQ0HWKRG (YHU\-DYDDSSOLFDWLRQPXVWFRQWDLQDVWDWLFPHWKRGZLWKWKH IROORZLQJVLJQDWXUHSXEOLFVWDWLFYRLGPDLQ 6WULQJ>@DUJV ¬ ­®¯#¯ ñ®³^¹Å±¯#¸K´ µ½¾ ­#³¬[¯¸®¸³¬ò· » ³Æ Ç® ³#¹R¿«È¸^¶ ³#¹ âɤÊË®#¶Ã¯À[´ ó »¶ ¿ ³¹ ¸ ³^Æô[Ìhõ¼ö³Æôq÷X®#¶Ã¯BÍk­^±¹ Ã@¸T²¼ø³Æ#ôÁ#Á@À[´ Ȥù¯ ¸S±ÇÍ«»^½¸BÍ=µ¶³^¹¸ ­^¹R¿ úû®¶#®^DZ¸S± ¶Kú Á{³Æ ô[Á úBüËú Ás® ¶Ã ¯rÉv³^ÆôÊ^À!¼    SAP AG 2004 For an application to be launched by the virtual machine (VM), it must contain a method with the name main, which must be written in the form: public static void main (String <variable>[]. String <...>[] defines a field of the type string. These are the command line parameters, which you can specify when you call the program. © SAP AG JA100 4-18 $FFHVVWRWKH,QVWDQFH&RQWH[WIURPWKH6WDWLF&RQWH[W $FFHVVWRLQVWDQFHPHWKRGVDQGLQVWDQFHDWWULEXWHV IURPWKHVWDWLFFRQWH[W z Create an instance within the static method. z Access the instance context via this instance. ÙÚ ÓÑÑ æ Õï ÞÙÚ ÕÛ ÜBÝÞß ÓÒÕ âÒ ÝÞàã Ù × Ú × Ý6á Ü Ðä ÚÞ Ù ÑÒ ÓÒ Þ@Ùhß × Þ å Ö@Ó Þ#à ç«â Ò ÝÞàã/ý|þ Ó Ýã Ñ@èIÛ æBÕ ï ÞÙÚ ÕKÖëæ@Õï Þ ÙÚ Õ é à Õÿ æ!Õï Þ@ÙÚ Õ;çHè á Öëæ Õï ÞÙÚ ÕJìgÑ^ÕÒ#ê × Ú × Ý ç nä Ú Ð@Õ è á í í Ü Ðä ÚÞ ÙXß × Þå Ñ^ÕÒ#ê × Ú × Ý çNâÒ ÝÞàã Ù × Ú × ÝKé Óê@× Ú × ÝRá í Óê@× Ú × Ý èxÛ SAP AG 2004 © SAP AG JA100 4-19 0RGLILHU [0] [1] FODVV 1DPH!>H[WHQGV 1DPH!@>LPSOHPHQWV 1DPH!@^ // Attributes 0 GDWDW\SH!QDPH! [2] [3] [4] [5] // Constructors: [2] QDPH! // Methods: [2] [1] [3] [5] >SDUDP>@@ ^ ` >SDUDP>@@ >WKURZV H[FHSWLRQ!@ ^ ` UHWXUQW\SH!QDPH! ` [0] [1] !"#%$& [2] '!() ! *+, - [3] . [4] [5] %$ (,/& SAP AG 2004 © SAP AG JA100 4-20 &ODVV 0RGLILHUV % '6 [0] &1! 2435 % 7 8 9 &1! 2A@ :;=<?> ; :B<C “can instantiate” “can instantiate” FODVV 7HVWB^ LPSRUW [\$ $DQ$ %D% QHZ $ QHZ % FODVV 7HVWB^ $DQ$ ` QHZ $ ` SAP AG 2004 Modifiers specify in a class declaration how the class is to be handled during further development. 0RGLILHU 0HDQLQJ SXEOLF The class is also visible outside the package. GHIDXOW You cannot use this class outside the package. Classes that are defined as SXEOLF can be imported from classes outside the package with the import statement. © SAP AG JA100 4-21 $WWULEXWHDQG0HWKRG 0RGLILHUV [2] % + - public class 8 D!E+F!G H I H JLKNM O D!E+F!G H IQPRH S T+U6K%VW XZY)[ \?]!^;_ `%a class with \?]!^;_ `%a A/M public class p D!qH P;r6KBU H J#KtsO D!qH P;r6KBU PRH Svu;wyx z{ |*}.O \h]!^;_ `%a class with \ij`lkmn o A/M 7:;j<C bcLde f~ &&&1+ 243 5 &&1L 2A@ b&cde%f~ & b cLde fg &1+&2A35 & &1+&2A@ SAP AG 2004 To define attributes and methods, you have the following modifiers (and others): 0RGLILHU 0HDQLQJ SXEOLF Method/attribute is visible from everywhere. SULYDWH Method/attribute is only visible within the same class You also have the SURWHFWHG modifier and the GHIDXOW! modifier for attributes and methods. © SAP AG JA100 4-22 7KHILQDO0RGLILHU [4] ,%$& &RQVWDQWV Ü Ð#ä ÚÞ@Ù ììì Ù Ú ÓÑÑ ð Ó Òï Ü Ðä Ú@ÞÙ í >VWDWLF@ILQDO Û ÑÒÓ@Ò ÞÙ Þ à Ó Újå ×Ðä Ú Õ é ì6&h!" ? ? ? á ì ìì SAP AG 2006 You can use the ILQDO modifier to create a variable that cannot be changed (constant). © SAP AG JA100 4-23 (QXPHUDWLRQV (QXPHUDWLRQVXVLQJSXEOLF VWDWLFILQDOYDULDEOHV • Up to and including J2SE 1.4.2, Java does not contain an enumeration type. Constants used to simulate Ö data types with values taken from a small, constant value list. Not typesafe SAP AG 2006 Up to and including J2SE 1.4.2, there is no enumeration type in Java. As a result, constants are frequently used to make the source code more descriptive. Integer constants are typically used for this, as can be seen in the seasons example above. This procedure is not satisfactory because the compiler cannot check if an integer value used is part of the enumeration, and is therefore valid or not. This means that this procedure is not typesafe. © SAP AG JA100 4-24 (QXPHUDWLRQV 7\SHVDIH HQXPHUDWLRQV XVLQJHQXP o&]+ • Declaration using key word • You can create Enums in separate files or within classes. • Enums are translated into classes by the compiler. • Enum values are objects of the type of the generated class. -6( SAP AG 2006 As of J2SE 5.0, proper enumerations are possible. The key word HQXP has been introduced for this. You can use it to declare an enumeration type using the following syntax: enum type name {VALUE, VALUE2, …} - The names of the elements are usually written in upper case. In the example shown, you can thus define a ' Season'data type that contains the values Season.SPRING, Season.SUMMER, Season.FALL and Season.WINTER as permitted values. Using the type name Season, a variable is then declared to which the value Season.SUMMER is assigned. An enumeration can be created in a separate file, as in the above example, or it can be defined within a class. An enumeration type is translated into a class that is derived from the superclass Enum (see also the unit "Inheritance and Interfaces"). Its values are realized as instances of this generated class. The value of an enumeration type is represented internally using an integer value. Therefore, enumeration types can be used in switch statements. Comparisons of values can be implemented using the == operator. Because enumeration types are translated into classes, in addition to the values, the declaration can also contain attributes and methods to offer additional functions. Using static imports (see above), enumeration types can be used very smartly: import static com.sap.training.Season.*; //... Season mySeason = 6800(5; © SAP AG JA100 4-25 &RQVWUXFWRU0RGLILHUV [2] ! - p D+E!F;G H I D!E!F+G H I > C { }6[ D+q)H Pr6KlU { }6[ &1+235 &&1L 2A@ { }#[ D!qH P;ryKBU { }#[ :; =<C 7:B<h> 7HVWB can instantiate from $ : 7HVWB can instantiate from $and % : ÙÚ ÓÑÑ ÕÑ Ò+tIÛ Þ Ö Ü × Ý Ò Ó à é à Õÿ çHè á Ó é à Õÿ çkè á ë%ì á ÙÚ Ó ÑÑ Õ!ÑÒ+\Û Ó à é à Õÿ Hç è á í í SAP AG 2006 By using one of the following modifiers, you can determine by whom an object of a class can be created: 0RGLILHU 9LVLELOLW\ SXEOLF Constructor is visible to all. A class can be instantiated from any other class. SULYDWH Constructor is only visible in the current class. Only methods of the defining class itself can use the constructor. © SAP AG JA100 4-26 5HOHDVLQJ 2EMHFWV 5HDFKDEOH 8QUHDFKDEOH 7KH REMHFW LV UHIHUHQFHG 7KHREMHFWLVQRORQJHU UHIHUHQFHG 7KHJDUEDJHFROOHFWRUFDOOV WKHILQDOL]H PHWKRGDQG UHOHDVHVWKHPHPRU\DUHD t U;¡!H I!G U (¢¤£ £ .j%$%$2h£ ¢'(?£ ¥/ ¦§>>>+¨ ©> ììì æ@Õï ÞÙ Ú ÕXÖ ëæ!Õï Þ ÙÚ Õ é ììì Öë æ Õï ÞÙ Ú Õ é à Ð ÚÚ á ììì à Õÿ æ Õï ÞÙÚ Õ;çHè á t U;¡!H I!G U ª U!QRqB SAP AG 2004 The garbage collector provides Java with automatic memory management. This asynchronous background job takes the task of releasing occupied memory away from the developer. Before the garbage collector releases the memory reserved for the object, its destructor is called. Destructors are called immediately before an object is destroyed. A destructor is defined as a method with no parameters, called finalize(). The destructor is always called by means of the garbage collector, which runs asynchronously. This means that destructors may be called late or, in some circumstances, never. © SAP AG JA100 4-27 *UDSKLF 'LVSOD\ 'LVSOD\LQJDFODVVLQWKH80/ 8QLILHG 0RGHOLQJ /DQJXDJH ÙÚ ÓÑÑ æ Õï ÞÙÚ ÕÛ ÜBÝÞß ÓÒÕ âÒ ÝÞàã Ù × Ú × Ýá ÜBÝÞß ÓÒÕxÑÒÓ Ò ÞÙCÞà Ò à >×+ ß Õï ÞÙ Ú Õ Ñ á Ü Ð#ä ÚÞ Ù æÕï ÞÙ Ú Õ/ç«â Ò ÝÞàã Ù × Ú × Ýhé Óê × Ú × ÝRá à × ß Õï Þ ÙÚ Õ!Ñ îî_á í Ó ê× Ú × Ý èIÛ Ü Ð#ä ÚÞ Ù[ß × Þå ÑÕÒ#ê × Ú × Ý çnâÒ ÝÞàã Ù × Ú × Ýhé Óê × Ú × ÝRá í í Óê × Ú × Ý èÛ Ü Ð#ä ÚÞ Ù ÑÒ ÓÒ Þ ÙCÞ à Ò ã Õ@Ò;« >×+ ß Õ ï ÞÙ Ú Õ Ñ_çNèÛ Ý Õ@Ò Ð Ý à à × ß Õï ÞÙÚ Õ!Ñ á í z 6WDWLFDWWULEXWHVDQGPHWKRGV DUHXQGHUOLQHG z 9LVLELOLW\ DUHDV SXEOLF SULYDWH SAP AG 2004 Several types of graphical representation were developed in object-oriented modeling theory to display the structure of and connections between classes. Since approximately 1995, the Unified Modeling Language (UML) has also developed from this. © SAP AG JA100 4-28 *UDSKLF 'LVSOD\ 6HTXHQFHGLDJUDPRI WKH80/ ¬!­+® ¯+¯ °&±+²³+¬;­L±;´± ¯+µ·¶ ¸ ¹yº­+³!¬»¯!µ®µL³¬½¼¾³¿ À&®;³;ÁtÂjõÄ;³LÁ!ÅQÆ ÇÈ®+Ä+Å ¯!Éʶ ° ±L² ³+¬!­L±ËÀÌ;° ±L²³!¬!­L± ÍÈÎ Á+±+Ï ° ±+²³¬;­L±t Ð.º&­L¹;±Ð ÉÑ ÃµyijLÁ+ÅZ¬!¾;­ÒÎËÀÌ° ±+²³!¬­+±Í?ÓÅ!± µyÔ!¾ ­+¾!ÄÂÉÑ ° ±L² ³+¬!­L±ËÀÌ;° ±L²³!¬!­L±;էΠÁ+±+Ï ° ±+²³¬;­L±t Ð#ÄL±;¿Ð É?Ñ ¬!¾!­§ÎËÀÌL° ±²³L¬;­+±!ÕÓÅ+±&µLÔ¾!­+¾!ÄÂÉÑ Ö Ö Lifeline Control focus SAP AG 2004 Sequence diagrams are used to illustrate certain processes or situations. For sequence diagrams, the chronological process of the behavior is in the foreground: y Creating and deleting objects y Message exchange between objects In the UML notation, lifetimes of objects are represented by vertical lines, which are provided with a rectangle with the object name. A cross signifies the end of the lifetime. The control focus is presented as a vertical column on the lifeline of the object. The control focus shows the active periods of the object. An object is active by carrying out actions or indirectly active by waiting on the end of a subordinate procedure. The messages are illustrated as horizontal arrows between the object lines. The message is noted on these in the form of a message (parameter). © SAP AG JA100 4-29 6XPPDU\ <RXVKRXOGQRZEHDEOHWR z 'HILQH FODVVHV z &UHDWHDWWULEXWHVDQGPHWKRGVLQFODVVHV z $SSURSULDWHO\LPSOHPHQWYLVLELOLW\DUHDVIRUDWWULEXWHV DQGPHWKRGV z &UHDWHLQVWDQFHVRIFODVVHVDQGUHUHOHDVH WKHP z &DOO XSPHWKRGV z 8VH FRQVWUXFWRUV SAP AG 2004 © SAP AG JA100 4-30 ([HUFLVH 8QLW 2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF &ODVVHVDQG2EMHFWV At the conclusion of these exercises, you will be able to: • Define classes • Create objects • Call up methods 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 1-1 1-2 1-3 1-4 1-5 6WDUW8S.LW FRPVDSWUDLQLQJVRO Create a new project in the development environment with the name 0\3URMHFW. Define the 0\3URMHFW?ELQ file as the output folder. In doing this, you will store the class files in another file from the Java files. Create the FRPVDSWUDLQLQJH[F package within your project. Define the &DU class in your package, which should contain two attributes with the associated set/get methods. Use the UML illustration of the &DU class below as a guide when implementing: In your packagecreate the 7HVWB$ class to test your &DU class. When defining the 7HVWB$ class, let the wizard create a PDLQ method. In the main method of the class 7HVWB$, create two objects of the &DU class. Call up the set methods for both of these objects to fill the attributes of both of the &DU objects. When doing so, use the sequence diagram below to help you. © SAP AG JA100 4-31 1-6 Read the attribute values from the objects again via the get methods and enter these values on the console. When doing so, use the sequence diagram below to help you. You can use the following syntax for the console output: 6\VWHPRXWSULQWOQ « As an argument, you must transfer the character string to be issued on the console to the SULQWOQ method. 1-7 Execute the test program. 6HTXHQFHGLDJUDPIRUH[HUFLVH © SAP AG JA100 4-32 6ROXWLRQ 8QLW 7RSLF 2EMHFW2ULHQWHG3URJUDPPLQJ &ODVVHVDQG2EMHFWV FODVV Car { SULYDWH String make; SULYDWH LQW mileage; SXEOLF String getMake() { UHWXUQ make; } SXEOLF LQW getMileage() { UHWXUQ mileage; } SXEOLF YRLG setMake(String string) { make = string; } SXEOLF YRLG setMileage(LQW i) { mileage = i; } } © SAP AG JA100 4-33 SXEOLF FODVV Test_A { SXEOLF VWDWLF YRLG main(String[] args) { Car myCar1 = QHZ Car(); Car myCar2 = QHZ Car(); myCar1.setMake("BMW"); myCar1.setMileage(2457); myCar2.setMake("Ford"); myCar2.setMileage(85736); String makename = myCar1.getMake(); LQW kmCount = myCar1.getMileage(); System.out.println("Attributes of car 1: " + makename + " " + kmCount); makename = myCar2.getMake(); kmCount = myCar2.getMileage(); System.out.println("Attributes of car 2: " + makename + " " + kmCount); } } © SAP AG JA100 4-34 ([HUFLVH 8QLW 2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF &ODVVHVDQG2EMHFWV At the conclusion of these exercises, you will be able to: • Create static attributes • Create and call up static methods • Define constructors 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 2-1 2-2 6WDUW8S.LW FRPVDSWUDLQLQJVRO In the &DU class, first define a static attribute that should take the number of &DU instances created in the program. Create a static get method for this attribute. Use the class diagram below as a guideline. Create a constructor in the &DU class. This should have two interface parameters through which you can transfer a manufacturer and a kilometer mileage for the car. In the implementation of the constructor, make sure that the values transferred via the interface are entered in the PDNH and/or PLOHDJH attributes. Maintain the instance counter in the constructor implementation. Use the class diagram below as a guide in this task. © SAP AG JA100 4-35 2-3 Change to the test class 7HVWB$ from the previous exercise. Adapt the existing syntax there to create two &DU instances in the PDLQ method by supplying the interface of the constructor. The existing call-up of the set methods in the coding for supplying the attributes is no longer required and can be deleted. 2-4 Before creating both &DU instances, call up the static get method for the instance counter you created above in the PDLQ method and transfer the return values to the console. 2-5 After creating the two &DU instances, repeat the call-up of the static get methods and the issue of your return value. The call-up of the get methods for reading the instance attribute values, as well as the issue of these attribute values on the console, can be transferred unchanged from the previous exercise. 2-6 Execute the test program. 2SWLRQDO 2-7 Make sure that the instance counter is decremented in case a &DU instance is deleted. 1RWH Java does not know any destructors to destroy instances. In Java, deleting the instances is done by the garbage collector. Make sure that one of your two &DU instances can be deleted by the garbage collector. You can achieve this by assigning QXOO to one of the two object variables. If, after initializing the object variable with QXOO, you query the content of the instance counter via the get method and issue on the console, you will see that this has not yet been decremented. To achieve this, you have to implement the ILQDOL]Hmethod in the &DU class as follows: SURWHFWHGYRLGfinalize()WKURZVThrowable { objCnt--; } The ILQDOL]H method is called up by the runtime system at the point when the object is finally destroyed by the garbage collector. Under certain conditions this may be carried out not until progam end or never (!!). To influence the processing time of the ILQDOL]H method, you can insert the following syntax after initializating the &DU object variable into your PDLQ method: System.gc(); Calling System.gc() makes it possible within the Java code to propose the immediate memory cleanup to the virtual machine. The decision about the actual cleanup at a certain time, however, continues to lie with the runtime system. This means that you cannot be absolutely sure whether the call-up of System.gc() actually leads to the processing of the ILQDOL]H method. 2-8 © SAP AG JA100 Test your application. 4-36 6ROXWLRQ 8QLW 7RSLF 2EMHFW2ULHQWHG3URJUDPPLQJ &ODVVHVDQG2EMHFWV SXEOLF FODVV Car { SULYDWH String make; SULYDWH LQW mileage; SULYDWHVWDWLFLQWREM&QW SXEOLF&DU 6WULQJPDNHLQWPLOHDJH ^ WKLVPDNH PDNH WKLVPLOHDJH PLOHDJH REM&QW ` SXEOLF String getMake() { UHWXUQ make; } SXEOLF LQW getMileage() { UHWXUQ mileage; } SXEOLF YRLG setMake(String string) { make = string; } SXEOLF YRLG setMileage(LQW i) { mileage = i; } } SXEOLFVWDWLFLQWJHW2EM&QW UHWXUQREM&QW ` RSWLRQDO SURWHFWHGYRLGILQDOL]H REM&QW ` © SAP AG ^ WKURZV7KURZDEOH^ JA100 4-37 SXEOLF FODVV Test_A { SXEOLF VWDWLF YRLG main(String[] args) { LQWFQW &DUJHW2EM&QW 6\VWHPRXWSULQWOQ 1XPEHURIFDUVFQW &DUP\&DU QHZ&DU %0: &DUP\&DU QHZ&DU )RUG FQW &DUJHW2EM&QW 6\VWHPRXWSULQWOQ 1XPEHURIFDUVFQW P\&DUVHW0DNH %0: P\&DUVHW0LOHDJH P\&DUVHW0DNH )RUG P\&DUVHW0LOHDJH String makename = myCar1.getMake(); LQW kmCount = myCar1.getMileage(); System.out.println("Attributes of car 1: " + makename + " " + kmCount); makename = myCar2.getMake(); kmCount = myCar2.getMileage(); System.out.println("Attributes of car 2: " + makename + " " + kmCount); } RSWLRQDO P\&DU QXOO 6\VWHPJF FQW &DUJHW2EM&QW 6\VWHPRXWSULQWOQ 1XPEHURIFDUVFQW } © SAP AG JA100 4-38 ([HUFLVH 8QLW 2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF &ODVVHVDQG2EMHFWV At the conclusion of these exercises, you will be able to: • Overload the constructors 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 3-1 3-2 3-3 6WDUW8S.LW FRPVDSWUDLQLQJVRO Define in this &DU class another private instance attribute for the license plate of the car. Create a set method and a get method for this attribute. Use the class diagram below as a guideline. In addition to the already existing constructor in the &DU class, create a second constructor. The manufacturer, the kilometer mileage and the car registration plate should be transferred via this constructor. Use the class diagram below as a guide in this task. Implement the additional constructor so that all instance attributes are supplied with the transferred values. To do this, call up the existing constructor from the construction implementation. In your packagecreate the 7HVWB% class as a test. When defining the 7HVWB% class, let the wizard create a PDLQ method. © SAP AG JA100 4-39 3-4 In the PDLQ method of class 7HVWB%, create two objects of the &DU class: one instance via the constructor with two interface parameters, and one instance via the just-created constructor with three interface parameters. 3-5 Finally, enter for both vehicles the content of all instance attributes on the console. 3-6 Execute the test program. The sequence diagram shown here illustrates the process flow for you. 6HTXHQFHGLDJUDPIRUWKHH[HUFLVH © SAP AG JA100 4-40 6ROXWLRQ 8QLW 7RSLF 2EMHFW2ULHQWHG3URJUDPPLQJ &ODVVHVDQG2EMHFWV SXEOLF FODVV Car { SULYDWH String make; SULYDWH LQW mileage; SULYDWH6WULQJOLFHQVH3ODWH SULYDWH VWDWLF LQW objCnt; SXEOLF Car(String make, LQW mileage) { WKLV.make = make; WKLV.mileage = mileage; objCnt++; } SXEOLF&DU 6WULQJPDNHLQWPLOHDJH6WULQJOLFHQVH3ODWH ^ WKLV PDNHPLOHDJH WKLVOLFHQVH3ODWH OLFHQVH3ODWH ` SXEOLF String getMake() { UHWXUQ make; } SXEOLF LQW getMileage() { UHWXUQ mileage; } SXEOLF YRLG setMake(String string) { make = string; } SXEOLF YRLG setMileage(LQW i) { mileage = i; } SXEOLF VWDWLF LQW getObjCnt() { UHWXUQ objCnt; } © SAP AG JA100 4-41 SXEOLF6WULQJJHW/LFHQVH3ODWH UHWXUQOLFHQVH3ODWH ` ^ SXEOLFYRLGVHW/LFHQVH3ODWH 6WULQJVWULQJ ^ OLFHQVH3ODWH VWULQJ ` } SXEOLF FODVV Test_B { SXEOLF VWDWLF YRLG main(String[] args) { Car myCar1 = QHZ Car("Ford", 34685); Car myCar2 = QHZ Car("BMW", 86436, "HD-JA 4341"); System.out.println( "Attributes of car 1: " + myCar1.getMake() + " " + myCar1.getMileage() + " " + myCar1.getLicensePlate()); System.out.println( "Attributes of car 2: " + myCar2.getMake() + " " + myCar2.getMileage() + " " + myCar2.getLicensePlate()); } } © SAP AG JA100 4-42 ([HUFLVH 8QLW 2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF &ODVVHVDQG2EMHFWV At the conclusion of these exercises, you will be able to: • Implement relations between classes (associations) 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJVRO 3UHOLPLQDU\&RQVLGHUDWLRQV In this exercise, you will add the &DU3RRO class to the already created &DU class. This new class acts as a data container to buffer several &DU instances. Here, the &DU instances are held by the type &DU in an array, which is to be defined as an attribute of the &DU3RRO class. 4-1 In your FRPVDSWUDLQLQJH[F packagecreate the class &DU3RRO. Define a constant 322/B6,=( with the value within this class as well as an array for the type &DU with the length of 322/B6,=(. Use the class diagram below as a guideline. © SAP AG JA100 4-43 4-2 4-3 Define a parameterless constructor for the &DU3RRO class. In the implementation of this constructor, create five &DU instances with any attribute values and add the references to these instances in the &DU array shown above. Finally, create the three access methods you can recognize in the class diagram on the &DU array in the &DU3RRO class: • The JHW&DU LG[LQW method should return the entry of the array to the LG[ position. • The DGG&DU LG[LQWFDU&DU method inserts the transferred &DU references on the LG[ position into the array. • The JHW6L]H method returns the length of the array. 4-4 4-5 In your FRPVDSWUDLQLQJH[F packagecreate the 7HVWB& class as a test. Get the wizard to create a PDLQmethod for you. Instantiate an object of the &DU3RRO class as well as an object of the &DU class in the PDLQ method of your test class with freely selectable attribute values. Add the reference to the created &DU instance via the DGG&DU method at any place in the data container and then issue the attribute values of all &DU objects contained in the data container on the console. Program a IRU loop for this via the entries in the data container. To gain access to the &DU instances buffered in the data container, call up the JHW&DU method for the &DU3RROinstance in the loop body. Use the sequence diagram below as a guideline. © SAP AG JA100 4-44 4-6 Execute the test program. 6HTXHQFHGLDJUDPIRUWKHH[HUFLVH © SAP AG JA100 4-45 © SAP AG JA100 4-46 6ROXWLRQ 8QLW 7RSLF 2EMHFW2ULHQWHG3URJUDPPLQJ &ODVVHVDQG2EMHFWV SXEOLF FODVV CarPool { SULYDWH VWDWLFILQDO LQW POOL_SIZE = 5; SULYDWH Car[] cars = QHZ Car[POOL_SIZE]; SXEOLF CarPool() { cars[0] = QHZ Car("BMW", 39487); cars[1] = QHZ Car("Ford", 354); cars[2] = QHZ Car("VW", 76423); cars[3] = QHZ Car("Opel", 234643); cars[4] = QHZ Car("BMW", 1232); } SXEOLF Car getCar(LQW idx) { UHWXUQ cars[idx]; } SXEOLF YRLG addCar(LQW idx, Car car) { cars[idx] = car; } SXEOLF LQW getSize() { UHWXUQ POOL_SIZE; } } SXEOLF FODVV Test_C { SXEOLF VWDWLF YRLG main(String[] args) { CarPool pool = QHZ CarPool(); Car myCar = QHZ Car("test", 99999); pool.addCar(1, myCar); IRU (LQW i = 0; i < pool.getSize(); i++) { © SAP AG JA100 4-47 Car car = pool.getCar(i); System.out.println(car.getMake() + " + car.getMileage()); " } } } © SAP AG JA100 4-48 ([HUFLVH 8QLW 2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF &ODVVHVDQG2EMHFWV At the conclusion of these exercises, you will be able to: • Implement a Java class as singleton 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJVRO 3UHOLPLQDU\FRQVLGHUDWLRQV From the &DU3RRO class created in the last exercise, you can create any number of instances within your application via the following syntax: CarPool pool1 = QHZ CarPool(); CarPool pool2 = QHZ CarPool(); ... In this exercise, the &DU3RRO class should be modified in such a way that it can now create only one instance. A class from which you can only create one instance is described as a VLQJOHWRQ. With this socalled draft design, the singleton class itself is responsible for creating the individual instance. You also have to provide an access method that enables clients to access the created instance within the class. 5-1 Implement the &DU3RRO class in your FRPVDSWUDLQLQJH[F package as a singleton. Use the diagram below as a guide when modifying the existing coding. 5-1-1 5-1-2 © SAP AG Reduce the visibility of the constructor of the &DU3RRO class from SXEOLF to SULYDWH. In this way, you prevent instantiation from outside the class of objects of the &DU3RRO type. Define a method within the &DU3RRO class through which a reference to the &DU3RRO instance still to be created is returned to the caller. This method must be defined as static, as it is called by a client without him being able to previously create an object of the class. JA100 4-49 5-1-3 5-2 To implement the access method you have just created, create an attribute of the type &DU3RRO class in the &DU3RRO class. Using this attribute, you ensure that only one instance of the &DU3RRO class is created. In the implementation of the access method, query whether this attribute is initial. If this is the case, create an instance of the &DU3RRO class, save the reference to this instance in the attribute and, after that, return the content of the attribute to the caller as the return value of the method. If the attribute is not initial, return the content of the attribute that is the reference to the individual instance via the interface. The attribute has to be defined as static so that you can access it in the static access method. Adjust your test class 7HVWB& in the FRPVDSWUDLQLQJH[F package. To access the &DU3RRO instance, you can no longer use the QHZ operator, but must call up the static access method created above. The rest of the text class can be transferred as it is. © SAP AG JA100 4-50 Execute the test program. The sequence diagram shown here illustrates the process flow for you. 6HTXHQFHGLDJUDPIRUWKHH[HUFLVH 5-3 © SAP AG JA100 4-51 © SAP AG JA100 4-52 6ROXWLRQ 8QLW 7RSLF 2EMHFW2ULHQWHG3URJUDPPLQJ &ODVVHVDQG2EMHFWV SXEOLF FODVV CarPool { SULYDWH VWDWLFILQDOLQW POOL_SIZE = 5; SULYDWH Car[] cars = QHZ Car[POOL_SIZE]; SULYDWHVWDWLF&DU3RROFDU3RRO QXOO SXEOLFVWDWLF&DU3RROJHW,QVWDQFH LI FDU3RRO QXOO ^ FDU3RRO QHZ&DU3RRO ` UHWXUQFDU3RRO ` ^ SULYDWH CarPool() { cars[0] = QHZ Car("BMW", 39487); cars[1] = QHZ Car("Ford", 354); cars[2] = QHZ Car("VW", 76423); cars[3] = QHZ Car("Opel", 234643); cars[4] = QHZ Car("BMW", 1232); } SXEOLF Car getCar(LQW idx) { UHWXUQ cars[idx]; } SXEOLF YRLG addCar(LQW idx, Car car) { cars[idx] = car; } SXEOLF LQW getSize() { UHWXUQ POOL_SIZE; } } © SAP AG JA100 4-53 SXEOLF FODVV Test_C { SXEOLF VWDWLF YRLG main(String[] args) { &DU3RROSRRO &DU3RROJHW,QVWDQFH Car myCar = QHZ Car("test", 99999); pool.addCar(1, myCar); IRU (LQW i = 0; i < pool.getSize(); i++) { Car car = pool.getCar(i); System.out.println(car.getMake() + " " + car.getMileage()); } } } © SAP AG JA100 4-54 ([HUFLVH 8QLW 2EMHFW2ULHQWHG3URJUDPPLQJ 7RSLF &ODVVHVDQG2EMHFWV At the conclusion of these exercises, you will be able to: • Implement a whole/parts relationship (aggregation) between classes 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJVRO 3UHOLPLQDU\FRQVLGHUDWLRQV In this exercise, you will extend the object model from the previous exercises by the :KHHO class. A whole/parts relationship (aggregation) should be implemented between this class and the already created &DU class. This means that a car should have wheels as individual parts. 6-1 6-2 6-3 Create the class :KHHO in your FRPVDSWUDLQLQJH[Fpackage as shown in the diagram below. Both attributes of the class should be supplied with values via the constructor, which you have to create. To map the aggregate relationship between the class &DU and the class :KHHO, declare an array variable for the type :KHHOin the&DUclass. Later, the partial objects (that is, the wheels) will be referenced via this attribute. Create a set method and a get method for this attribute. Create another constructor in the &DUclass through which the wheel objects are created. This constructor should have four interface parameters (see class diagram). First, call up one of the two already existing constructors of the &DUclass from the implementation of the constructor in order to transfer the manufacturer and the kilometer mileage. The :KHHOobjects are created using the two other interface parameters. Now create the method FUHDWH:KHHOV in the &DUclassas outlined in the class diagram. In this method, create a local :KHHO array with a length of IRXU and fill this with four :KHHO objects that you create using the properties transferred via the method interface. After that, return the :KHHO array as a return value to the caller. © SAP AG JA100 4-55 6-3-1 6-4 6-5 Now call up the FUHDWH:KHHOV method from the newly created constructor and transfer the properties of the wheels to it. These are transferred to the constructor via the interface. Assign the return value of the FUHDWH:KHHOV method to the array variables created under 6-2. To test the aggregation relationship, &DUobjects should now be instantiated via the constructor created in step 6-3. Adapt the implementation of the &DU3RRO class to this in your FRPVDSWUDLQLQJH[F package. In the constructor of this class, a &DU array is filled with references to &DU instances. Modify the creation of these &DU objects by using the constructor you just created for the instantiation. In your FRPVDSWUDLQLQJH[F packagecreate the 7HVWB' class as a test. Get the wizard to create a PDLQmethod for you. Then create a &DU3RRO instance in this PDLQ method. Obtain the reference to any buffered &DU object from this instance using the JHW&DU method. Subsequently, you can obtain the associated :KHHOarray for this &DU object via JHW:KHHOV . Finally, export the properties of the individual :KHHOobjects from this array via a loop to the console. © SAP AG JA100 4-56 Execute the test program. The sequence diagram shown here illustrates the process flow for you. 6HTXHQFHGLDJUDPIRUWKHH[HUFLVH 6-6 © SAP AG JA100 4-57 © SAP AG JA100 4-58 6ROXWLRQ 8QLW 7RSLF 2EMHFW2ULHQWHG3URJUDPPLQJ &ODVVHVDQG2EMHFWV SXEOLF FODVV Wheel { SULYDWH IORDW size; SULYDWH ERROHDQ aluminumWheel; SXEOLF Wheel(IORDW size, ERROHDQ aluminumWheel) { WKLV.size = size; WKLV.aluminumWheel = aluminumWheel; } SXEOLF ERROHDQ isAluminumWheel() { UHWXUQ aluminumWheel; } SXEOLF IORDW getSize() { UHWXUQ size; } SXEOLF YRLG setAluminumWheel(ERROHDQ b) { aluminumWheel = b; } SXEOLF YRLG setSize(IORDW f) { size = f; } } © SAP AG JA100 4-59 SXEOLF FODVV Car { SULYDWH String make; SULYDWH LQW mileage; SULYDWH String licensePlate; SULYDWH:KHHO>@ZKHHOV SULYDWH VWDWLF LQW objCnt; SXEOLF Car(String make, LQW mileage) { WKLV.make = make; WKLV.mileage = mileage; objCnt++; } SXEOLF Car(String make, LQW mileage, String licensePlate) { WKLV(make, mileage); WKLV.licensePlate = licensePlate; } SXEOLF&DU 6WULQJPDNH LQWPLOHDJH IORDWZKHHO6L]H ERROHDQDOXPLQXP:KHHO ^ WKLV PDNHPLOHDJH ZKHHOV FUHDWH:KHHOV ZKHHO6L]HDOXPLQXP:KHHO ` SXEOLF String getMake() { UHWXUQ make; } SXEOLF LQW getMileage() { UHWXUQ mileage; } SXEOLF YRLG setMake(String string) { make = string; } SXEOLF YRLG setMileage(LQW i) { mileage = i; } SXEOLF VWDWLF LQW getObjCnt() { UHWXUQ objCnt; © SAP AG JA100 4-60 } SXEOLF String getLicensePlate() { UHWXUQ licensePlate; } SXEOLF YRLG setLicensePlate(String string) { licensePlate = string; } SULYDWH:KHHO>@FUHDWH:KHHOV IORDWZKHHO6L]H ERROHDQDOXPLQXP:KHHO ^ :KHHO>@ZKHHOV QHZ:KHHO>@ IRU LQWL LZKHHOVOHQJWKL ^ ZKHHOV>L@ QHZ:KHHO ZKHHO6L]HDOXPLQXP:KHHO ` UHWXUQZKHHOV ` SXEOLF:KHHO>@JHW:KHHOV UHWXUQZKHHOV ` ^ SXEOLFYRLGVHW:KHHOV :KHHO>@ZKHHOV ^ WKLVZKHHOV ZKHHOV ` } SXEOLF FODVV CarPool { SULYDWH VWDWLFILQDO LQW POOL_SIZE = 5; SULYDWH Car[] cars = QHZ Car[POOL_SIZE]; SULYDWH VWDWLF CarPool carPool = QXOO; SXEOLF VWDWLF CarPool getInstance() { LI (carPool == QXOO) { carPool = QHZ CarPool(); } UHWXUQ carPool; } SULYDWH CarPool() { FDUV>@ QHZ&DU %0:WUXH FDUV>@ QHZ&DU )RUGIDOVH FDUV>@ QHZ&DU 9:WUXH FDUV>@ QHZ&DU 2SHOWUXH FDUV>@ QHZ&DU %0:WUXH © SAP AG JA100 4-61 } SXEOLF Car getCar(LQW idx) { UHWXUQ cars[idx]; } SXEOLF YRLG addCar(LQW idx, Car car) { cars[idx] = car; } SXEOLF LQW getSize() { UHWXUQ POOL_SIZE; } } © SAP AG JA100 4-62 SXEOLF FODVV Test_D { SXEOLF VWDWLF YRLG main(String[] args) { CarPool pool = CarPool.getInstance(); System.out.println("\nWheels of car at index 3:"); Car myCar = pool.getCar(3); Wheel[] wheels = myCar.getWheels(); IRU (LQW i = 0; i < wheels.length; i++) { LQW j = i + 1; System.out.print("Wheel " + j); System.out.print(" Size " + wheels[i].getSize()); System.out.println( " aluminum-wheel: " + wheels[i].isAluminumWheel()); } } } © SAP AG JA100 4-63 © SAP AG JA100 4-64 ,QKHULWDQFHDQG,QWHUIDFHV &RQWHQWV z ,QKHULWDQFH z &DVWV z 3RO\PRUSKLVP z ,QWHUIDFHV SAP AG 2004 © SAP AG JA100 5-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z ,PSOHPHQWLQKHULWDQFHUHODWLRQVKLSVEHWZHHQFODVVHV z 'HILQH DQGLPSOHPHQW LQWHUIDFHV z 3HUIRUPXSFDVWV DQGGRZQFDVWV z 'HVFULEH DQGXVH SRO\PRUSKLVP SAP AG 2004 © SAP AG JA100 5-2 ,QKHULWDQFH 5HODWLRQVKLSV 80/QRWDWLRQ Vehicle color volume 6XSHUFODVV getColor() setColor() getVolume() setVolume() 7UXFN ,QKHULWDQFH LV DUHODWLRQVKLS &DU 6XEFODVV SAP AG 2004 Inheritance enables the user to derive new classes from existing classes. This results in a formal association that allows a specific class (subclass) to reuse the attributes and the method of a less specific class (superclass). y The subclass inherits all attributes and methods of the superclass and usually contains additional attributes and methods. y The FODVVWUHH resulting from inheritance can have an infinite nesting depth. y In Java, each class has exactly one direct superior class (single inheritance). However, each class can have an infinite number of subclasses. In Java, the primary class of all classes is REMHFW This class represents the blueprint for all other classes. If no superclass is specified in a class definition, Java assumes that the new class is directly derived from REMHFW. © SAP AG JA100 5-3 ,QKHULWDQFH 5HODWLRQVKLSV 'HULYLQJ FODVVHV FODVV FODVVQDPH! H[WHQGV QDPH! "! #! • Relationship of the type “A is a B”, for example, “Car is a vehicle” • A superclass is a JHQHUDOL]DWLRQ of its subclasses. • A subclass is a VSHFLDOL]DWLRQ of its superclass. $ "! ³H[WHQGV´ GRHVQRWDOORZPXOWLSOH LQKHULWDQFH ,QKHULWDQFHDOORZVXVHUVWRUHXVHH[LVWLQJSURJUDPFRGHDQGWR FXVWRPL]HLWIRUWKHLURZQSXUSRVHV SAP AG 2004 One of the most important design characteristics of object-oriented languages is the combining of variables and methods in classes. Another important principle is inheritance, which allows the transfer of attributes and methods of existing classes to new classes. To derive a new class from an existing class, you must specify a reference to the superclass in the header of the new class using the keyword H[WHQGV. Now, the derived class inherits all attributes and methods of the superclass. The functions of the derived class can be enhanced using $GG, 2YHUORDG or 2YHUZULWH for methods. Java doesQRWsupport multiple inheritance. You can specify only RQHsuperclass after H[WHQGV. Note that single inheritance does not mean that the inheritance tree has only one level. This is not the case, because the direct superclass of a class can be a subclass of another superclass. In other words, the inheritance tree can have an infinite depth; a class can inherit indirectly from many superclasses, but only from one directly. © SAP AG JA100 5-4 7KH MDYDODQJ2EMHFW &ODVV %'&)(*&,+ - &/.)0 2EMHFW 7KH REMHFW FODVV LVWKHURRWRIWKHFODVVKLHUDUFK\LQ-DYD • All classes are derived explicitly or implicitly from REMHFW. • Therefore, all methods of REMHFW are available in all Java classes. SAP AG 2004 The class java.lang.Object has a central role due to its status as a root class. For example, it can be used to define data structures that can include any type of objects. © SAP AG JA100 5-5 2YHUZULWH 0HWKRGV "! 12 43 5 6798 Vehicle + estimateFuel(distance:int):float :;! "! 12 43 5 67<8 :=! 7UXFN "! 12 43 5 6798 + estimateFuel(distance:int):float :;! &DU + estimateFuel(distance:int):float SAP AG 2004 Methods that were inherited from the parent class can be redefined in the subclass. When redefining a method in a derived class, the original method is overwritten. Therefore, all calls refer to the overwritten method. In Java, method calls are interpreted dynamically (dynamic binding), that means the compiler cannot decide which method is executed. Therefore it must generate code that decides in runtime which method is executed. This can have a considerable effect on runtime performance. To avoid this, the following options are available for achieving static binding: y The SULYDWH modifier Methods ot the type SULYDWH are not visible in derived classes and cannot therefore be overwritten. y The ILQDOmodifier Explicitly definining the method with the ILQDOmodifier prevents you from overwriting the method. y The VWDWLFmodifier Methods of the type VWDWLFexist independently from an instance. These methods are not interpreted dynamically. © SAP AG JA100 5-6 $FFHVV&RQWURO '\QDPLF ELQGLQJ Vehicle At runtime, the method to be processed is searched for in the class hierarchy from bottom to top. + estimateFuel(distance:int):float $FFHVVFRQWURO When overwriting, you may increase the visibility of the original method. >6? A@ B <8C:ED 35 3 FD 3G@H6? )6 $7I8*JKK:ED 7UXFN + estimateFuel(distance:int):float &DU + estimateFuel(distance:int):float SAP AG 2004 When creating subclasses and overwriting methods, you must consider the access control of the original methods. In general, the following applies: superclass public protected <default> derived class public protected or public <default>, protected, or public When you call up an object method, the search for the implementation is made hierarchically from bottom to top in the inheritance hierarchy until the desired method is found. © SAP AG JA100 5-7 .H\ZRUG VXSHU Vehicle + estimateFuel(distance:int):float "! 12 P35 $6 7Q8 :;! "! 1 2 P35 )6 7I8 :R! 7UXFN + estimateFuel(distance:int):float 3 5 S TU3H@ ) 1 )6 7I8V :UD VXSHU &DU + estimateFuel(distance:int):float SAP AG 2004 >6? H@ B 98C:LD 3 5 3MD 3H@A6? )6 $7I8NJKK:OD When redefining a method in a derived class, the original method is overwritten. Java provides the keyword VXSHUso that you can call the original implementation of a method when overwriting. However, a cascading call (for example, super.super.meth()) is not allowed. © SAP AG JA100 5-8 ,QKHULWDQFH DQG&RQVWUXFWRUV Constructors cannot be inherited. super([<param.>]) calls a constructor of the superclass. #! 1 S WXa55 bD 1 2 c8'W X4 5 5:;! 55G@a 55FD Explicit call of a VXSHUFODVV constructor "! 1 2 I8CW XP5 5LY 6X :=! 1 8' 55 : D >6?FD 6?H@ B I8 Z[2Z Y]\^_\\:`D SAP AG 2004 When an object creates a class, the Java compiler calls not only the suitable constructorbut may also call a constructor of the parent class. Since constructors cannot be inherited, they must be called with super() if they are needed in a derived class. Therefore, when creating a new object, several constructors along the inheritance hierarchy are called. © SAP AG JA100 5-9 WKLVVXSHUDQGWKHFRQVWUXFWRU 1 S$ 1 S$ #! WXG6 5bD WXG6 MD 1 2 d8C:=! 6 5 @ e))6 1G6 5 Ue D 6 @ e))6 1G6 e D X @ eNffPff#__e D 65g@hJ KKKED @ 3 D 1 2 d8iW Xg6 5 bY]W X>6 :=! $ 8j:`D 6 5 G@H6 5bD 6 @H6 MD SAP AG 2006 "! 12 I8N:=! 1 8 e _\H5 62 e , eW $2Fe : D If you overload a constructor, you should not program a function twice. You can do this by using this() to ensure a mutual calling of the constructors. In the above example, the constructor of the class Car calls a constructor of the superclass Vehicle. In turn, the vehicle constructor called uses this() to call another constructor of the same class. © SAP AG JA100 5-10 7KH ILQDO 0RGLILHU )LQDO&ODVVHV DQG0HWKRGV Final classes have no subclasses. Final methods cannot be overwritten in subclasses. &RQVWDQWV >VWDWLF@ILQDO 12 k3 k l#! 12 k 43P 52 mn @=o J^J\_)p q \o\r_s_op or^q D SAP AG 2004 A ILQDO class cannot contain subclasses and is therefore protected against (uncontrolled) specialization. A ILQDO method cannot be redefined in any of its subclasses and is therefore protected against (uncontrolled) redefining. You can use the modifier ILQDO to create an unchangeable (constant) variable. © SAP AG JA100 5-11 7KH DEVWUDFW 0RGLILHU $EVWUDFW&ODVVHV DQG0HWKRGV Abstract classes cannot themselves be instantiated (but their subclasses can be). Abstract methods are defined in a class, but are not implemented. They must be overwritten in the subclasses. )2 > #! 12 A$2OH35 $6 7t8 :`D Abstract method "! 12 P35 $6 7<8 :=! is implemented in a derived class SAP AG 2004 Abstract classes cannot be instantiated. They can be considered an incomplete construction plan for concrete (that is, non-abstract) subclasses (for example, specifying uniform interfaces). Abstract methods contain only the declaration of the method header, not an implementation of the method body. They cannot be called, but only define an interface that can be implemented by overwriting in a derived class. Abstract instance methods predefine a certain interface for subclasses, without having to provide them with an implementation. A class containing at least one abstract method must also have the keyword DEVWUDFW © SAP AG JA100 5-12 ,QKHULWDQFH0RGLILHU RI&ODVVHV [0] v uc/ zVw v {i [1] wx{*wu${`jNwv v uIuv wxx v u9wx{Cwu${ uv wxx v utCwv uv w$xx uv wxx wx{Cwu${uv wxx Nwv[uv w$xx “can instantiate” “can be derived from” [TOJ;! @ B 8j: D 4 @ B Q8j: D @ B 8j: D 747 @ B 7Q8j: D [TOJ [TOJ [TOJ [TOJ ! # ! ! # ! [T p! @ B 8j: D 4 @ B Q8j: D [T p [T p ! #! wu[w zt uv w$x x y zx{| w u[wz< uv wxx yzx{}|~ SAP AG 2004 Modifiers specify in a class declaration how the class is to be handled during further development. 0RGLILHU SXEOLF Classes can also be seen outside the package. <GHIDXOW! ILQDO 0HDQLQJ DEVWUDFW Classes cannot be used outside the package. Classes may not be derived. You cannot create instances of classes. Classes that are defined as SXEOLF can be imported from classes outside the package with the LPSRUW instruction. © SAP AG JA100 5-13 ,QKHULWDQFH$WWULEXWHDQG0HWKRG0RGLILHUV [2] v uc)¼»{´z u){´z ½,z´wv {´¾¹ N ¿w{Vz public class uv w$xx yzx{| public class A Public class with public attributes and methods uv wxx Á $| Public class with protected attributes and methods uv wxx Á` $| ¯µ¹¥[¶jµ[·¹®U¨¯¸ ¯µ/¥)¶jµ/·)®Uà /µ/¥)¶jµ/·)®`¨/¸ ¯µ/¥)¶jµ¹·[®`à uv wxx y zx{}|~ uv wxx Á` $|~ public class uv wxx yz$x{}| uv wxx y zx{|~ uv wxx Á` $|~ public class ¤ ¦º§E¨© ª«¤ ¬Â­¹®,§° ±}²t³}© uv wxx y zx {| [À¼¤ ªµ¯§® ¤ ¦,§E¨© [À¼¤ ªµ¯§® ª «¤ ¬L­/®¯§ °±}²9³}© Public class with default attributes and methods uv wxx Á` $| uv wxx Á` $| uv wxx Á` $|~ Public class with private attributes and methods /µ/¥)¶ºµ/·[®`¨/¸ /µ/¥)¶jµ/·)®`¨/¸ ¯µ¹¥[¶jµ[·¹®Uà uv w$xx y zx {| [À}«¹§®/¥,§®[¬ ¤ ¦[§E¨© [À}«¹§®/¥,§®[¬Oª«¤ ¬ ­¹®¯§ ° ±²9³¼© )¡)¢)£ ¤ ¥ ¤ ¦[§E¨ © )¡)¢)£ ¤ ¥`ª«¤ ¬M ­/®¯§ °±}²t³´© uv wx x y z$x{}| ~ /µ/¥)¶ºµ/·[®Uà uv wxx Á` $| ~ uv wxx y zx{|~ SAP AG 2004 Overview of the modifiers for defining the visibility of attributes and methods: 0RGLILHU SXEOLF SURWHFWHG GHIDXOW! SULYDWH © SAP AG 0HDQLQJ Visible from everywhere Only visible within the same package and in derived classes Only visible within the same package Only visible within the same class JA100 5-14 3RO\PRUSKLVP Vehicle &DOOLQJGLIIHUHQWPHWKRG LPSOHPHQWDWLRQVIURPGLIIHUHQW FODVVHVXVLQJRQHDQGWKH VDPHV\QWD[ + estimateFuel(distance:int):float "! 1 2 k35 6 798 :=! 7UXFN + estimateFuel(distance:int):float ÄÅÆ ÇÇ È ÉÊÄË ÌÍÎÌ ÏÐ Ç Ñ Ì ÒÓÄ Å Ì#Ô Õ ÊÖÅ ÓÄk×ÅØÆÎ ÌÇÎ ÓÙÆÎÌÚÊÌÅ9Û ÓÏ Î ÐÓ ÇÎ ÆÏ ÄÌ`ÜRÔ ÝÝÝ Þ Þ &DU ÄÅÆÇÇ ß ÆÉ ÌÍÎÌÏÐ Ç ÑÌÒÓÄ Å Ì"Ô Õ ÊÖÅ ÓÄk×ÅØÆÎ ÌÇÎ ÓÙÆ ÎÌÚÊÌÅ9Û ÓÏÎ ÐÓ ÇÎÆÏÄÌ Ü;Ô + estimateFuel(distance:int):float Ý ÝÝ Þ Þ SAP AG 2004 Polymorphism through inheritance is enabled by your ability to overwrite methods in subclasses. This allows you to send a message to objects of different classes, which will then return different responses. The called method is always the one directly assigned to the class. © SAP AG JA100 5-15 8SFDVW 8SFDVW î ®$ï[¤ ¥)£ ® ÄÅ ÆÇÇ Ñ ÌÒÓÄÅÌ"Ô ÝÝ Ý Þ ð µ)À A subclass instance can always be used where its superclass type is expected. ÄÅ ÆÇÇ ÝÝ Ý Þ ß ÆÉ ÌÍÎÌÏÐ Ç ÑÌ ÒÓÄ Å Ì"Ô ÄÅÆÇÇ ßÆÇÎÓ Ï àÈÌÇ Î;Ô ÕÊÖ`ÅÓ ÄáÇÎÆÎÓÄGâ Ø ÓÐ ÙÆÓÏãÛ*äÎÉÓÏàkÆÉàÇtå,æ$Ü;Ô ÑÌÒÓÄ ÅÌgÙçÑÌÒÓÄÅÌbè ßÆÉ>Ùçß ÆÉHé ÏÌê ßÆÉtÛ Ý ÝÝ ÜUè ÙçÑ ÌÒÓÄÅ ÌPéHÙ çßÆÉLè ëëgÊÕ`Ä ÆÇÎ Æ[ìÌÎ$ÒØÐíÛÙçßÆÉÜOè Þ Þ ÕÊÖ`ÅÓÄ ÝÝÝ Þ ÆìÌÎ)ÒØÐdÛÑ ÌÒ Ó ÄÅÌaÆ[Ñ ÌÒ Ó ÄÅÌÜ=Ô SAP AG 2004 One of the main principles of inheritance is that a subclass instance can be used in every context where the type of its superclass is expected. This is possible because the subclass inherits all components of the superclass. Therefore, users can call the subclass instance in the same way as they would call the superclass instance. Only the view of the corresponding objects changes. The objects themselves or their attributes/methods remain the same. Assigning an instance of a subclass to a reference variable of the type UHIHUHQFHWRVXSHUFODVV is known as an upcast (or widening cast). © SAP AG JA100 5-16 8SFDVW 3ULQFLSOH RIWKH 8SFDVW 6ZLWFKLQJIURPDGHWDLOHGYLHZWRDOHVVGHWDLOHGYLHZ õU¸ ð µ$À õO¸ î ®$ï)¤ ¥)£ ® ð µ$Àöc÷,ø¯µ)¢¯ù¹ú ß ÆÉñÙçß ÆÉHé ÏÌ ê ßÆÉ9Û Ý ÝÝ Ü`è ÑÌÒÓÄÅÌHÙçÑÌÒÓÄÅÌFè zx{C ûcw{Vz zv ü'ý½þ Ù çÑ Ì ÒÓÄ ÅÌPéHÙçßÆ Ébè ×ÅØ ÆÎ ×ÊÌÅHé Ù çÑ ÌÒÓÄ ÅÌ Ý ÌÇÎ ÓÙÆÎÌÚ ÊÌÅ9ÛjòóóÜLè ëëôÙçÑÌÒÓÄ Å Ì Ý àÌÎä[ÕÌÌÐcÛCÜEè zx{N ûcw{´z zv üNýÿþ z${´Á`zz üþ õU¸ ð µ$À õO¸ î ®$ï)¤ ¥)£ ® ð µ$Àöd÷jø¯µ¢ºù[ú ð µÀöc÷ºø¯µ)¢,ù[ú zx{C ûcw{Vz zv ü'ý½þ zx {C ûcw{Vzzv ü'ý½þ z{VÁ`zzü¼þ SAP AG 2004 After executing the upcast, you can access the components of the &DU instance that were inherited from &DU using the reference object variable P\9HKLFOH. There may be restrictions due to their visibility (modifier). The object variable P\9HKLFOH no longer enables you to access the &DU-specific part of the instance (getSpeed() method, in the example shown above). © SAP AG JA100 5-17 3RO\PRUSKLVP 8VLQJ ,QKHULWDQFH ÄÅÆÇÇ Ñ Ì ÒÓ ÄÅÌÈÌÇÎhÔ ÕÊÖ ÅÓ ÄkÇÎÆÎ Ó ÄHâ Ø Ó Ð ÙÆÓ ÏãÛNäÎ É Ó Ï à4ÆÉàÇ å¹æÜ;Ô Ñ ÌÒÓÄÅÌ<å¹æôÆß ØÏÎÆÓÏÌÉHé Æ ßØÏ Î ÆÓ Ï ÌÉQåNó æ é Æ ßØÏ Î ÆÓ Ï ÌÉQå*òæ é × ÅØ ÆÎ Þ Þ Ï Ìê Ï Ìê ÏÌê Ñ ÌÒÓÄ ÅÌ<å æ è ß ÆÉQÛÜLè È É ÊÄË<Û ÜLè ×ÊÌÅFè ×ØÉ Û ÓÏÎ ÓÐÍkéRóUè ÓÐÍ è ÓÐÍ ÜaÔ ×ÊÌ Å éaÆß ØÏÎÆÓÏÌÉtåNÓÐÍ`æ Ý ÌÇÎÓÙÆÎ$ÌÚÊÌÅ<Û òó óÜ`è Þ SAP AG 2004 The key to polymorphism through inheritance lies in the possibility of also using object variables of a superclass type for referencing subclasses objects. Objects of different classes can be treated in the same way. However, in the method call, the respective specific subclass methods are used. © SAP AG JA100 5-18 'RZQFDVW 'RZQFDVW î ®)ï$¤ ¥)£ ® ÄÅ Æ ÇÇ Ñ ÌÒÓ ÄÅÌÔ ÝÝÝ Þ ð µÀ ÄÅÆÇÇ ÝÝ Ý Þ No safe conversion from the superclass to the subclass cast is required! ßÆÉ ÌÍÎÌÏÐ Ç ÑÌÒÓÄÅÌÔ ÄÅÆÇÇ ßÆÇ ÎÓ Ï àÈÌÇÎ Ô ÕÊÖ ÅÓÄkÇÎÆÎ Ó ÄHâ ØÓÐ ÙÆÓÏ Û*äÎ É ÓÏàaÆÉàÇ å¹æÜ=Ô ß ÆÉ>ÙçßÆÉHé ÏÌê ß ÆÉIÛ Ý ÝÝ Ü è ÑÌ ÒÓÄ ÅÌGÙçÑÌÒ Ó ÄÅÌFè ÙçÑ ÌÒÓÄÅÌPéGÙçßÆ Ébè ëë>ÊÕÄ ÆÇÎ Ó × ÛÙçÑÌÒ Ó ÄÅÌ ÓÏÇÎÆÏ ÄÌØ× ß ÆÉÜ;Ô Þ Þ Þ ßÆÉ>ÙçßÆ É éãÛ´ßÆÉÜ ÙçÑ ÌÒÓÄ Å Ìtè ë ëGÐØêÏÄ ÆÇÎ SAP AG 2004 Only an explicit cast allows the conversion of a superclass to a subclass. You must verify that the cast actually created a reference to a subclass instance. © SAP AG JA100 5-19 'RZQFDVW 3ULQFLSOH RIWKH 'RZQFDVW 6ZLWFKLQJIURPDOHVVGHWDLOHGYLHZWRDGHWDLOHGYLHZ SURYLGHGWKDWXSFDVW ZDVSUHYLRXVO\H[HFXWHG õO¸ î ®$ï)¤ ¥)£ ® ð µ)Àöc÷ºø,µ¢ºù[ú Ù çÑ Ì ÒÓÄ ÅÌPéHÙçßÆ Ébè ëëgÊÕÄÆÇÎ õU¸ ð µ$À ð µ$Àöc÷jø/µ$¢ºù)ú õO¸ ð µÀ ßÆÉñÙçß ÆÉ è z$x{N ûcw{´z zv üNýÿþ z{´Á`zz üVþ Ó× Þ ÛÙçÑ ÌÒ Ó ÄÅÌ Ùçß ÆÉ é õO¸ î ®$ï)¤ ¥)£ ® ð µ$Àöc÷ºø/µ)¢,ù¹ú Ó ÏÇÎÆÏÄÌØ× ßÆÉÜ=Ô ëëGÐ ØêÏÄÆÇ Î ÛCßÆÉÜ ÙçÑÌ Ò ÓÄÅÌ ; õO¸ ð µÀ ð µ)Àöc÷ºø,µ¢ºù[ú õU¸ ð µ$À ð µÀöc÷ºø¯µ)¢¯ù¹ú z$x{N ûcw{´z zv üNýÿþ z{´Á`zz üVþ SAP AG 2004 The downcast (or narrowing cast) is the opposite of the upcast. The downcast cannot be checked statically; a check can only be executed at runtime. It is checked at runtime whether or not the current content of the source variable meets the type requirements of the target variable. If this is the case, the assignment is executed. Otherwise, a (catchable) runtime error is triggered. The downcast in the example above does not cause an error because the object variable P\9HKLFOH actually refers to an instance of the subclass &DU. © SAP AG JA100 5-20 '\QDPLF 7\SH6SHFLILFDWLRQ ÄÅÆÇÇ Ñ Ì ÒÓ ÄÅÌÈÌÇ Î;Ô uv w$xx z uv z ÕÊÖ ÅÓÄkÇÎÆÎ Ó ÄHâØ ÓÐ ÙÆÓÏãÛNäÎ É Ó Ï à4ÆÉàÇ å¹æÜ;Ô Ñ Ì ÒÓÄÅÌ<å¹æôÆßØÏÎ ÆÓÏÌÉHé Æ ßØ Ï Î ÆÓ Ï ÌÉQåCó æ]é Æ ßØ Ï Î ÆÓ Ï ÌÉQåNò æ]é uv wxx Ow uv w$xx yiu ¥$£ µ¯­¯­¦,µ[õ`® ¥/« õ ­[µ) §¼Àµ$¤ ¦[¤¦¹· ¬[®õE« ð µ$À î ®)ï$¤ ¥$£ ® ð µ$À ¥$£ µ¯­¯­¦,µ[õ` ® ¥/« õ ­[µ) §¼Àµ$¤ ¦[¤¦¹· ¬[®õE« ÀV¡¯¥$¶ î ®)ï$¤ ¥$£ ® À¼¡/¥)¶ Þ Þ Ï Ìê Ï Ìê ÏÌê Ñ ÌÒÓÄÅÌ<å æ è ßÆÉQÛ ÝÝ Ý ÜLè ÈÉÊÄË<Û ÝÝ Ý ÜEè ×ØÉ Û ÓÏÎ Ó Ð ÍPéRóOè Ó Ð Í è Ó Ð ÍÜ=Ô ä çÇÎÌÙ Ý ØÊÎ Ý Õ ÉÓ ÏÎ ÅÏ<Û ÄÅÆÇ Ç$ÏÆ)Ù Ì PÆßØÏÎÆÓ Ï ÌÉIåiÓÐÍ`æ Ý à ÌÎßÅ Æ ÇÇ9ÛNÜ Ý àÌÎÆ ÙÌíÛNÜ ÜLè Ó× Û'Æß ØÏÎÆÓ ÏÌ ÉtåNÓ Ð Í æ ÓÏÇÎÆÏÄÌØ× ÑÌÒ Ó ÄÅÌÜ=Ô ä$ç`ÇÎÌÙ Ý ØÊÎ Ý ÕÉ Ó ÏÎÅÏQÛ ÑÌÒ Ó ÄÅ Ì Ü è Þ Ó× Û'Æß ØÏÎÆÓ ÏÌ ÉtåNÓ Ð Í æ ÓÏÇÎÆÏÄÌØ× ßÆÉÜ;Ô ä$ç`ÇÎÌÙ Ý ØÊÎ Ý ÕÉ Ó ÏÎÅÏQÛ ßÆ É ÜUè Þ Ó× Û'Æß ØÏÎÆÓ ÏÌ ÉtåNÓ Ð Í æ ÓÏÇÎÆÏÄÌØ× ÈÉÊ ÄËÜRÔ ä$ç`ÇÎÌÙ Ý ØÊÎ Ý ÕÉ Ó ÏÎÅÏQÛ ÈÉÊ Ä Ë Ü`è Þ Þ SAP AG 2004 With the method JHW&ODVV of the class 2EMHFW, a random object has the ability to deliver a suitable FODVVREMHFW. For every class that the runtime system uses, a class object of the type &ODVV is created during the loading process. The class &ODVV provides methods for querying properties of the class. The method JHW1DPH returns the class name as a character string. String name = <Object>.getClass().getName(); The LQVWDQFHRI operator can also be used to find out to which class a particular object belongs. The LQVWDQFHRI operator has two operands: an object on the left, and the class name on the right. The expression DLQVWDQFHRIE returns the result WUXH if a is an instance of the class b or is one of its subclasses. © SAP AG JA100 5-21 ,QWHUIDFHV Interfaces describe services of classes, but do not have implementations themselves. ,QWHUIDFHV Describe which services (technical and semantic) are required for processing a task 3URYLGHU VHUYHU Derives a concrete class from the interface and implements the corresponding function print and display print and display documents documents show file hierarchy show file hierarchy 8VHU FOLHQW Does not need to be familiar with the implementation, but only with the description of the interface. The user can be sure that the class will “behave as is specified by the interface”. SAP AG 2004 Interfaces are usually defined by the user. In interfaces, the user describes which services (technical and semantic) are required from the provider to process a task. The user does not know the actual providers. They communicate with them only via the interface. Therefore, the user is kept apart from the actual implementations and can use different types of classes and objects as long as they provide the required services (polymorphism via interfaces). The example above describes two interfaces. Both define what potential providers must be able to do: display and print themselves, and output a node for displaying the file directory. Two of the three providers provide all the services required, while the third provider only implements the services for the file browser. © SAP AG JA100 5-22 'HILQLQJ DQ,QWHUIDFH 'HILQLWLRQ PRGLILHU! LQWHUIDFH QDPH!>H[WHQGV LQWHUIDFH!>LQWHUIDFH!@@ ^ <interfacebody> ` IAccountHolder Õ ÊÖ ÅÓ ÄkÓÏ ÎÌÉ ×ÆÄÌ !ÄÄØÊ ÏÎ#"ØÅ ÐÌÉ Å ØÏà àÌ$Î UÄÄØ ÊÏÎØíÛNÜ è ÓÏÎ àÌ&Î %Æ ÏË ßØÐÌcÛNÜLè äÎÉÓÏà àÌ Î ÏâØÓ Ä 'Ì ÐÐÉÌÇÇ9ÛNÜLè Þ // getter methods // setter methods Interface attributes are implicitly SXEOLF VWDWLF ILQDO. Interface methods are implicitly SXEOLF DEVWUDFW. An interface corresponds to an abstract class with exclusively abstract methods. SAP AG 2006 Interfaces have a structure similar to many classes, but they differ from each other in the following ways: y An interface contains only constants (no variables) and methods. y The methods are only declared, not implemented. y An interface can have several super interfaces. An interface is defined by the keyword LQWHUIDFH. The compiler checks that the rules applying to interfaces are adhered to. © SAP AG JA100 5-23 ,PSOHPHQWLQJ DQ,QWHUIDFH ,PSOHPHQWDWLRQ FODVV FODVVQDPH! LPSOHPHQWV QDPH!>QDPH!@^` IAccountHolder Õ ÊÖ ÅÓÄ4ÄÅÆÇÇ (ÉÓâÆÎÌßÊÇÎØÙ ÌÉ ÓÙÕ`Å ÌÙ ÌÏÎÇ ÄÄ ØÊÏÎ#"ØÅÐÌÉ Ô Ý ÝÝ ÕÊÖ`ÅÓÄGÅØÏ à àÌ Î$`ÄÄØÊÏÎ) Ø9ÛjÜ Ô ëëGÐØ ÇØ ÙÌÎ$ÒÓÏ à Þ // getter methods // setter methods ÕÊÖ`ÅÓÄGÓÏÎ àÌÎ#%ÆÏËß ØÐ Ì<ÛºÜRÔ ëëGÐØkÇØ$ÙÌÎÒ ÓÏà Þ ð «$õM,µ)¦/¸ * À¼¤ ªµ,§® ð ¡,­/§«õ ®$À ÕÊÖ`ÅÓÄ ä Î É ÓÏà4àÌÎ $Ïâ ØÓÄÌ ÐÐ ÉÌÇ Ç ÛºÜRÔ ëëGÐØkÇØ$ÙÌÎÒ ÓÏà Þ Þ The implementation is provided in the individual classes. Interfaces allow you to provide the same methods for different classes that have nothing else in common, without having to create superclasses. SAP AG 2004 Implementing an interface in a class forces the class to implement the methods that were defined in the interface. All the methods in the interface must be programmed out, otherwise the class must be defined as an abstract. A class can implement any number of interfaces. © SAP AG JA100 5-24 ,QWHUIDFHVDV'DWD 7\SHV $QLQWHUIDFHFDQEHXVHGDVDGDWDW\SH $YDULDEOHW\SHGRQDQLQWHUIDFH LVILOOHGE\PHDQVRIDQDVVLJQPHQW IAccountHolder // getter methods // setter methods $QLQWHUIDFHYDULDEOHFDQSRLQWWRREMHFWV ZKRVHFODVVHVKDYHLPSOHPHQWHGWKHLQWHUIDFH ð «$õM,µ)¦/¸ * À¼¤ ªµ,§® ð ¡,­/§«õ ®$À Ä ÄØÊÏÎ+"ØÅÐ ÌÉkÆÄÄØ ÊÏÎ+" ØÅÐÌÉEè $ ÆÄÄØ ÊÏÎ'"ØÅÐÌÉHé ÅØ Ï à ÏÌê ( ÉÓâ ÆÎÌß ÊÇÎ ØÙÌÉ9Û ÝÝÝ ÜUè ÆÄÄØAéaÆÄÄØ ÊÏÎ"ØÅÐÌÉ Ý àÌ Î Ä ÄØÊÏÎØIÛ Ü`è SAP AG 2004 Every interface represents a reference data type, which can be used like other data types. References to objects whose classes implement the relevant interface, or one of the interfaces derived from these classes, can be assigned to interface variables. © SAP AG JA100 5-25 3RO\PRUSKLVP DQG,QWHUIDFHV IAccountHolder Õ ÊÖ ÅÓ ÄkÓÏÎÌÉ ×ÆÄ Ì long getAccountNo( ) … ð «)õF¯µ$¦/¸ * ÕÊÖ ÅÓÄPÄÅÆÇÇ À¼¤ ªµ,§® ð ¡,­/§«$õ ®$À ÄÄØ ÊÏÎ#"Ø Å ÐÌÉ Ô Ý ÝÝ Þ Õ ÊÖ ÅÓÄ4ÄÅ Æ ÇÇ ( ÉÓâÆÎÌßÊÇÎØ ÙÌÉ Ó[ÙÕ ÅÌÙÌ Ï ÎÇ !Ä ÄØÊÏ Î"ØÅ Ð ÌÉ Ô ÝÝÝ Þ Õ ÊÖ ÅÓ ÄkÄÅ Æ ÇÇ ß Ø$Ù ÕÆÏ ç Ó)Ù ÕÅÌ$ÙÌÏÎÇ $`ÄÄ Ø ÊÏÎ&"ØÅÐÌÉ;Ô ÝÝ Ý Þ Ï ÎÌ É×ÆÄÌÈÌÇÎhÔ Õ ÊÖ ÅÓ ÄáÇÎÆÎ Ó ÄHâØÓÐ ÙÆÓ ÏcÛCäÎÉ ÓÏà4ÆÉàÇFå¹æ$Ü=Ô (ÉÓâ ÆÎÌß ÊÇÎØ ÙÌÉ>ÕÉ ÓâßÊÇÎgé ÏÌê ( ÉÓâÆÎ$ÌßÊÇÎØ ÙÌÉtÛ Ý ÝÝ Ü`è ßØ$Ù ÕÆÏç Ä Ø ÙÕ ÆÏç é ÏÌê ß Ø$Ù ÕÆÏçcÛ ÝÝ Ý ÜLè ,Ä ÄØÊÏ& Î "ØÅ Ð Ì ÉPÆ-ß Ø ÏÎÆÓÏÌÉtå¹æ é Æß ØÏÎ ÆÓ ÏÌÉtåjóæ éHÕ ÉÓâßÊ ÇÎbè Æß ØÏÎ ÆÓ ÏÌÉtåºòæ éáÄØ)ÙÕ ÆÏçMè Þ ÅØÏ à ÅØÏ à Ï Ìê ÄÄØ ÊÏÎ#"ØÅÐÌÉtå æ è ! 3RO\PRUSKLVP ÆÄ ÄØ òñéaÆ.ßØÏÎÆÓ Ï Ì É<å*ó æ Ý à ÌÎ ÄÄØÊÏÎØíÛ*ÜLè ÆÄ Ä Ø éa. Æ ßØÏÎÆÓ Ï Ì É<å òæ Ý à ÌÎ ÄÄØÊÏÎØíÛ*ÜLè Þ SAP AG 2004 interface IAccountHolder is implemented from both the class 3ULYDWH&XVWRPHU and the class &RPSDQ\. The In the above example, an array of length two of the type of the interface IAccountHolder is defined. This array can hold references to such objects whose classes have implemented the interface IAccountHolder. The interface method getAccountNo()can be called for the objects referenced via the array. © SAP AG JA100 5-26 3RO\PRUSKLVP,QKHULWHQFHDQG,QWHUIDFHV 3RO\PRUSKLVP 8VLQJ ,QKHULWDQFH Applies to objects of classes that are connected with each other in an inheritance hierarchy 3RO\PRUSKLVP 8VLQJ ,QWHUIDFHV Applies to objects of classes that implement the same interface SAP AG 2004 © SAP AG JA100 5-27 8VLQJ ,QWHUIDFHV 6HSDUDWLRQRIDEVWUDFW VSHFLILFDWLRQ LQWHUIDFHV DQGFRQFUHWH LPSOHPHQWDWLRQ FODVV / Client defines protocol, server implements it / “Black box” principle: Client only knows the interface, but not the implementation / Loose connection between client and server 3RO\PRUSKLVP / Generic treatment of objects of different classes $EVWUDFWLRQ / Interface as a generalization of the implementing classes 6LPXODWLRQRIPXOWLSOHLQKHULWDQFH ÕÊÖÅ ÓÄkÄÅÆ ÇÇ (É ÓâÆ Î$Ìß Ê`Ç ÎØ$ÙÌÉ ÌÍÎÌÏÐ Ç ÖUÇÎÉÆÄÎ+(ÌÉÇ$ØÏ ÓÙÕ Å ÌÙÌÏ ÎÇ !Ä ÄØÊÏÎ "ØÅ Ð ÌÉ Ô ÝÝÝ Þ SAP AG 2006 Interfaces are used to describe interfaces without involving a type of implementation. An additional layer is introduced between client and server that separates the client from the explicit server to make the client more independent. Interfaces enable you to handle the most diverse classes (providers) using a standard procedure. Their behavior is always polymorphic, because they do not have implementations themselves, but require them from the providers. The definition of an interface is always an abstraction. The users want to communicate with different providers and must therefore abstract from the concrete implementations a description of services that are required for processing their tasks. Interfaces can also be used for multiple inheritance. Functions that are to be inherited from a second class are defined as the interface that has to implement the inheriting class. © SAP AG JA100 5-28 6XPPDU\ <RXVKRXOGQRZEHDEOHWR z ,PSOHPHQWLQKHULWDQFHUHODWLRQVKLSVEHWZHHQFODVVHV z 'HILQH DQGLPSOHPHQW LQWHUIDFHV z 3HUIRUP XSFDVWV DQGGRZQFDVWV z 'HVFULEH DQGXVH SRO\PRUSKLVP SAP AG 2004 © SAP AG JA100 5-29 © SAP AG JA100 5-30 ([HUFLVH 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH At the conclusion of these exercises, you will be able to: • Implement an inheritance relationship between classes • Call a superclass constructor from the implementation of a subclass constructor • Overwrite methods in subclasses 6DPSOHVROXWLRQ: 3URMHFW 6WDUW8S.LW 3DFNDJH FRPVDSWUDLQLQJLQKHULWDQFHVRO 1-1 In your project 0\3URMHFW, create a new package with the name FRPVDSWUDLQLQJLQKHULWDQFHH[F. In this package, define the class 5RDG9HKLFOH in line with the class diagram shown below. The constructor of this class should accept values for the two attributes and transfer them into the attributes. In the method VKRZ3URSHUWLHV the content of all the attributes is output on the console by means of the statement 6\VWHPRXWSULQWOQ « . © SAP AG JA100 5-31 1-2 1-3 Create the classes 0RWRU%LNH and 7UXFN in the package FRPVDSWUDLQLQJLQKHULWDQFHH[F in line with the class diagram. They should be defined as subclasses of 5RDG9HKLFOH. You should implement the constructors of the two classes in such a way that they supply all the attributes of these classes (and also the inherited ones). First, call from the implementation of these constructors the constructor of the superclass 5RDG9HKLFOH. Then overwrite in the subclasses the method VKRZ3URSHUWLHV , inherited from 5RDG9HKLFOH, in such a way that all the attribute values are output on the console. In your package FRPVDSWUDLQLQJLQKHULWDQFHH[Fcreate the class 7HVW,QKHULWDQFH. Let the wizard create a PDLQmethod for you. In the PDLQmethod, create one object of the class 0RWRU%LNH and one object of the class 7UXFN. Then call the method VKRZ3URSHUWLHV for these two objects. © SAP AG JA100 5-32 Test your application. The sequence diagram shown here illustrates the process flow for you. 6HTXHQFHGLDJUDPIRUH[HUFLVH 1-4 © SAP AG JA100 5-33 © SAP AG JA100 5-34 6ROXWLRQ 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH SXEOLF FODVV RoadVehicle { SULYDWH String make; SULYDWH String tag; SXEOLF RoadVehicle(String make, String tag) { WKLV.make = make; WKLV.tag = tag; } SXEOLF YRLG showProperties() { System.out.print("Make: " + make + "\tTag: " + tag); } SXEOLF String getMake() { UHWXUQ make; } SXEOLF String getTag() { UHWXUQ tag; } SXEOLF YRLG setMake(String string) { make = string; } SXEOLF YRLG setTag(String string) { tag = string; } } © SAP AG JA100 5-35 SXEOLF FODVV MotorBike H[WHQGV RoadVehicle { SULYDWH ERROHDQ sideCar; SXEOLF MotorBike(String make, String tag, ERROHDQ sideCar) { VXSHU(make, tag); WKLV.sideCar = sideCar; } SXEOLF YRLG showProperties() { System.out.print("I’m a bike: \t"); VXSHU.showProperties(); System.out.println("\tSidecar } : " + sideCar); SXEOLF ERROHDQ isSideCar() { UHWXUQ sideCar; } SXEOLF YRLG setSideCar(ERROHDQ b) { sideCar = b; } } SXEOLF FODVV Truck H[WHQGV RoadVehicle { SULYDWH LQW numberOfAxles; SXEOLF Truck(String make, String tag, LQW numberOfAxles) { VXSHU(make, tag); WKLV.numberOfAxles = numberOfAxles; } SXEOLF YRLG showProperties() { System.out.print("I’m a truck: \t"); VXSHU.showProperties(); System.out.println("\tNumber of Axles: " + numberOfAxles); } SXEOLF LQW getNumberOfAxles() { UHWXUQ numberOfAxles; } SXEOLF YRLG setNumberOfAxles(LQW i) { numberOfAxles = i; } } © SAP AG JA100 5-36 SXEOLF FODVV TestInheritance { SXEOLF VWDWLF YRLG main(String[] args) { Truck myTruck = QHZ Truck("Volvo ", "HD-JA 4342", 6); MotorBike myMotorBike = QHZ MotorBike("Yamaha", "F-T 97", IDOVH); myTruck.showProperties(); myMotorBike.showProperties(); } } © SAP AG JA100 5-37 ([HUFLVH 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH At the conclusion of these exercises, you will be able to: • Perform upcasts • Implement polymorphic access to objects 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 2-1 2-2 2-3 2-4 6WDUW8S.LW FRPVDSWUDLQLQJLQKHULWDQFHVRO In your package FRPVDSWUDLQLQJLQKHULWDQFHH[Fcreate the class 8S&DVW,QKHULWDQFH. Let the wizard create a PDLQmethod for you. Within the PDLQmethod, define an array of the type of the class 5RDG9HKLFOH with a length of WZR. Fill this array with a reference to a 0RWRU%LNHinstance and a reference to a 7UXFN instance. Program a IRU loop over the array created. Call the method VKRZ3URSHUWLHV in the loop body for the individual array entries. Test your application. Which implementation of the method VKRZ3URSHUWLHV is processed in the individual loop runs? The debugger will help you understand the polymorphic behavior of your application. © SAP AG JA100 5-38 © SAP AG JA100 5-39 6ROXWLRQ 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH SXEOLF FODVV UpCastInheritance { SXEOLF VWDWLF YRLG main(String[] args) { RoadVehicle[] vehicleFleet = QHZ RoadVehicle[2]; vehicleFleet[0] = QHZ Truck("Volvo ", "F-I 24 ", 6); vehicleFleet[1] = QHZ MotorBike("Kawasaki", "B-TZ 98", WUXH); IRU (LQW i = 0; i < vehicleFleet.length; i++) { vehicleFleet[i].showProperties(); } } } © SAP AG JA100 5-40 © SAP AG JA100 5-41 ([HUFLVH &KDSWHU,QKHULWDQFHDQG,QWHUIDFHV 6XEMHFW,QKHULWDQFH At the conclusion of these exercises, you will be able to: • Perform downcasts • Use the LQVWDQFHRI operator to dynamically specify the type (class) of the object to which an object variable is pointing 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 3-1 3-2 3-3 FRPVDSWUDLQLQJLQKHULWDQFHVRO In your package FRPVDSWUDLQLQJLQKHULWDQFHH[Fcreate the class 'RZQ&DVW,QKHULWDQFH. Let the wizard create a PDLQmethod for you. Within the PDLQmethod, define for this class an array of the type of the 5RDG9HKLFOH class with a length of five. Fill this array with references to different 7UXFNand 0RWRU%LNH objects. You can select the attribute values of these objects as you wish. All 7UXFNobjects have the attribute QXPEHU2I$[OHV. It is now your task to specify the 7UXFN instance that has the highest value for this attribute, meaning the 7UXFN with the most axles in the array. To do this, implement a IRU loop over the 5RDG9HKLFOH array created above. In the body of the loo,. put the LQVWDQFHRI operator so that you can differentiate 7UXFNobjects from 0RWRU%LNHobjects. 3-3-1 3-3-2 3-4 6WDUW8S.LW Carry out a downcast for the 7UXFN objects to get a wide view of these instances. With the downcast, you get access to the attribute QXPEHU2I$[OHV of the 7UXFN instances (method JHW1XPEHU2I$[OHV ). You can thus identify the 7UXFN with the most axles. Output the properties of the 7UXFN instance found on the console. For this, use the method VKRZ3URSHUWLHV . Test your application. © SAP AG JA100 5-42 © SAP AG JA100 5-43 6ROXWLRQ 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH SXEOLF FODVV DownCastInheritance { SXEOLF VWDWLF YRLG main(String[] args) { RoadVehicle[] vehicleFleet = QHZ RoadVehicle[5]; vehicleFleet[0] = QHZ Truck("Volvo ", "M-OO 52", 4); vehicleFleet[1] = QHZ Truck("MAN ", "KL-R 2", 2); vehicleFleet[2] = QHZ MotorBike("Harley", "S-RR 235", WUXH); vehicleFleet[3] = QHZ Truck("Benz ", "N-L 6899", 8); vehicleFleet[4] = QHZ Truck("MAN ", "HH-K 97", 6); Truck truck, truckMax = QXOO; LQW axlesMax = 0; IRU (LQW i = 0; i < vehicleFleet.length; i++) { LI (vehicleFleet[i] LQVWDQFHRI Truck) { truck = (Truck)vehicleFleet[i]; LI (truck.getNumberOfAxles() > axlesMax) { axlesMax = truck.getNumberOfAxles(); truckMax = truck; } } } System.out.println("Here’s the biggest truck:"); truckMax.showProperties(); } } © SAP AG JA100 5-44 © SAP AG JA100 5-45 ([HUFLVH 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH At the conclusion of these exercises, you will be able to: • Define interfaces • Implement interfaces in server classes • Call the methods of an interface using instances of a server class 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 4-1 4-2 FRPVDSWUDLQLQJLQWHUIDFHVVRO In your package FRPVDSWUDLQLQJLQKHULWDQFHH[Fcreate the interface ,&DUJR&DUULHU. Use the class diagram below as a guideline. In your package FRPVDSWUDLQLQJLQKHULWDQFHH[Fcreate the class &DUJR6KLS. You can see the structure of this class in the class diagram. The constructor of this class supplies the values to the two attributes PD[&DUJR and PD[6SHHG. 4-2-1 4-3 6WDUW8S.LW In the class &DUJR6KLS, implement the interface ,&DUJR&DUULHU, which you created in step 4-1. As implementation of the interface method JHW0D[&DUJR:HLJKW , you return the value of the attribute PD[&DUJR. Adapt the implementation to the class 7UXFN in line with the class diagram. To do so, create the additional attribute SD\ORDG in the class, including the related set and get methods. 4-3-1 4-3-2 © SAP AG Extend the interface and the implementation of the constructor of the class 7UXFN, so that the SD\ORDGattribute is also supplied with a value when a 7UXFN object is instanced. Adapt the method VKRZ3URSHUWLHV in the 7UXFNclass. The content of the SD\ORDGattribute shall also be output on the console. Finally, implement the interface ,&DUJR&DUULHU in the class 7UXFN. You return the content of the attribute SD\ORDG as the return value of the interface method JHW0D[&DUJR:HLJKW . JA100 5-46 4-4 4-5 Create 7HVW,QWHUIDFHV to test the class. Let the wizard to create a PDLQmethod for you. Within this PDLQmethod, create one object of the class 7UXFN and one object of the class &DUJR6KLS. Call up the interface method JHW0D[&DUJR:HLJKW for these two objects and output the return value on the console. Test your application. 6HTXHQFHGLDJUDPIRUWKHH[HUFLVH © SAP AG JA100 5-47 © SAP AG JA100 5-48 © SAP AG JA100 5-49 6ROXWLRQ 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QWHUIDFHV SXEOLF LQWHUIDFH ICargoCarrier { SXEOLF IORDW getMaxCargoWeight(); } SXEOLF FODVV CargoShip LPSOHPHQWV ICargoCarrier { SULYDWH IORDW maxCargo; SULYDWH IORDW maxSpeed; SXEOLF CargoShip(IORDW maxCargo, IORDW maxSpeed) { WKLV.maxCargo = maxCargo; WKLV.maxSpeed = maxSpeed; } SXEOLF IORDW getMaxCargoWeight() { UHWXUQ maxCargo; } SXEOLF IORDW getMaxCargo() { UHWXUQ maxCargo; } SXEOLF IORDW getMaxSpeed() { UHWXUQ maxSpeed; } SXEOLF YRLG setMaxCargo(IORDW f) { maxCargo = f; } SXEOLF YRLG setMaxSpeed(IORDW f) { maxSpeed = f; } } © SAP AG JA100 5-50 SXEOLF FODVV Truck H[WHQGV RoadVehicle LPSOHPHQWV,&DUJR&DUULHU { SULYDWH LQW numberOfAxles; SULYDWHIORDWSD\ORDG SXEOLF Truck(String make, String tag, LQW numberOfAxles, IORDWSD\ORDG) { VXSHU(make, tag); WKLV.numberOfAxles = numberOfAxles; WKLVSD\ORDG SD\ORDG } SXEOLF YRLG showProperties() { System.out.print("I’m a truck: \t"); VXSHU.showProperties(); System.out.print("\tNumber of Axles: " + numberOfAxles); 6\VWHPRXWSULQWOQ ?W3D\ORDGSD\ORDG } SXEOLF LQW getNumberOfAxles() { UHWXUQ numberOfAxles; } SXEOLF YRLG setNumberOfAxles(LQW i) { numberOfAxles = i; } SXEOLFIORDWJHW0D[&DUJR:HLJKW UHWXUQSD\ORDG ` SXEOLFIORDWJHW3D\ORDG UHWXUQSD\ORDG ` ^ ^ SXEOLFYRLGVHW3D\ORDG IORDWI ^ SD\ORDG I ` } © SAP AG JA100 5-51 SXEOLF FODVV TestInterfaces { SXEOLF VWDWLF YRLG main(String[] args) { Truck myTruck = QHZ Truck("Volvo ", "HD-JA 4342", 4, 30); CargoShip myShip = QHZ CargoShip(5000, 15); IORDW maxCargo = myTruck.getMaxCargoWeight(); System.out.println("Max. Cargo of myTruck: " + maxCargo); maxCargo = myShip.getMaxCargoWeight(); System.out.println("Max. Cargo of myShip: " + maxCargo); } } © SAP AG JA100 5-52 © SAP AG JA100 5-53 ([HUFLVH 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH At the conclusion of these exercises, you will be able to: • Execute upcasts using interface variables • Implement polymorphic access to objects via interfaces 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJLQWHUIDFHVVRO 5-1 In your FRPVDSWUDLQLQJLQKHULWDQFHH[F packagecreate the class 8S&DVW,QWHUIDFHV. Let the wizard create a PDLQmethod for you. 5-2 Within the PDLQmethod, define an array of the type of the interface ,&DUJR&DUULHU with a length of WKUHH. Fill this array with references to 7UXFNand &DUJR6KLS instances. 5-3 5-4 Calculate the sum of the maximum freight weights for all the objects referenced in the array. To do this, apply polymorphism via the interfaces as follows: program a IRU loop via the array created and, in the loop body, call the interface method JHW0D[&DUJR:HLJKW for the individual array entries. Finally, output on the console the calculated sum of all the freight weights. Test your application. Which implementation of the method JHW0D[&DUJR:HLJKW is processed in the individual loop runs? The debugger will help you understand the polymorphic behavior of your application. © SAP AG JA100 5-54 © SAP AG JA100 5-55 6ROXWLRQ 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QWHUIDFHV SXEOLF FODVV UpCastInterfaces { SXEOLF VWDWLF YRLG main(String[] args) { ICargoCarrier[] aContainer = QHZ ICargoCarrier[3]; aContainer[0] = QHZ Truck("Volvo ", "F-I 24 ", 4, 7.5f); aContainer[1] = QHZ CargoShip(5000, 18); aContainer[2] = QHZ CargoShip(3000, 20); IORDW cargoSum = 0; IRU (LQW i = 0; i < aContainer.length; i++) { cargoSum = cargoSum + aContainer[i].getMaxCargoWeight(); } System.out.println("Total: " + cargoSum); } } © SAP AG JA100 5-56 © SAP AG JA100 5-57 ([HUFLVH 2SWLRQDO 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QKHULWDQFH At the conclusion of these exercises, you will be able to: • Perform downcasts using interface variables • Use the LQVWDQFHRI operator to dynamically specify the type (class) of the object to which an interface variable is pointing 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6-1 6-2 6-3 6WDUW8S.LW FRPVDSWUDLQLQJLQWHUIDFHVVRO In your package FRPVDSWUDLQLQJLQKHULWDQFHH[Fcreate the class 'RZQ&DVW,QWHUIDFHV. Let the Wizard create a PDLQmethod for you. Within the PDLQmethod of this class, define an array of the type of the interface ,&DUJR&DUULHU with a length of ILYH. Fill this array with references to different 7UXFNand &DUJR6KLS objects. You can select the attribute values of these objects as you wish. All &DUJR6KLSobjects have the attribute PD[6SHHG. Your task is to find the highest value of this attribute among the &DUJR6KLSinstances referenced in the array. To do this, implement a IRU loop over the ,&DUJR&DUULHU array created above. 6-3-1 In the body of the loop, apply the LQVWDQFHRI operator so that you can differentiate &DUJR6KLSobjects from 7UXFNobjects. Carry out a downcast for the &DUJR6KLS objects to get a wide view of these instances. With the downcast you get access to the attribute PD[6SHHG of the &DUJR6KLSinstances (method JHW0D[6SHHG ). You can thus specify the maximum speed of the fastest freight ship. 6-3-2 Finally, output the value found on the console. 6-4 Test your application. © SAP AG JA100 5-58 © SAP AG JA100 5-59 6ROXWLRQ 2SWLRQDO 8QLW ,QKHULWDQFHDQG,QWHUIDFHV 7RSLF ,QWHUIDFHV SXEOLF FODVV DownCastInterfaces { SXEOLF VWDWLF YRLG main(String[] args) { ICargoCarrier[] aContainer = QHZ ICargoCarrier[5]; aContainer[0] = QHZ CargoShip(6000, 19); aContainer[1] = QHZ CargoShip(3000, 28); aContainer[2] = QHZ Truck("Volvo ", "M-OO 52", 4, 7.5f); aContainer[3] = QHZ CargoShip(5000, 21); aContainer[4] = QHZ Truck("MAN ", "HH-K 97", 8, 30); CargoShip cargoShip; IORDW speedMax = 0; IRU (LQW i = 0; i < aContainer.length; i++) { LI (aContainer[i] LQVWDQFHRI CargoShip) { cargoShip = (CargoShip) aContainer[i]; LI (cargoShip.getMaxSpeed() > speedMax) { speedMax = cargoShip.getMaxSpeed(); } } } System.out.println("The speed of the fastest Cargoship: " + speedMax); } } © SAP AG JA100 5-60 © SAP AG JA100 5-61 ([FHSWLRQV &RQWHQWV z %DVLFSULQFLSDOVRIH[FHSWLRQKDQGOLQJLQ-DYD z &UHDWLQJ\RXURZQH[FHSWLRQFODVVHV z 7ULJJHULQJKDQGOLQJDQGGHFODULQJH[FHSWLRQV SAP AG 2004 © SAP AG JA100 6-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z ([SODLQWKHFRQFHSWRIH[FHSWLRQKDQGOLQJLQ-DYD z $YRLGSURJUDPWHUPLQDWLRQVWKURXJKDSSURSULDWH HUURU KDQGOLQJ z &UHDWH\RXURZQH[FHSWLRQFODVVHV SAP AG 2004 © SAP AG JA100 6-2 %DVLFV 2EMHFW 7KURZDEOH 1 (UURU ([FHSWLRQ 2 3 9LUWXDO0DFKLQH(UURU « « « « 5XQWLPH([FHSWLRQ « ,QGLYLGXDOHUURUVDUHUHSUHVHQWHGE\H[FHSWLRQFODVVHV LQ-DYD (UURU (and all the classes derived from it) 1 Abnormal errors which should not be controlled by the program ([FHSWLRQ (and all the classes derived from it which are not subclasses of 2 RuntimeException) Errors which PXVW be controlled by the program 5XQWLPH([FHSWLRQ (and all the classes derived from it) 3 Errors that FDQbe controlled by the program SAP AG 2004 An exception refers to a situation during program execution that is different from the normal program flow (for example, access to a locked file). Such exceptions can be detected by the application and handled accordingly. The concept for exception handling greatly contributes to stability and security within Java. Java distinguishes between errors (java.lang.Error), which cause termination of the program, and exceptions (java.lang.Exception), after which the program can continue to be executed. The (UURU class that is used by Java internally is specified in API, but it is not intended for use by applications. Most of the errors already defined refer to internal errors of the interpreter – for example, errors during management of objects. Java programs should only work with objects of the class ([FHSWLRQ and its subclasses. © SAP AG JA100 6-3 'HILQLQJ<RXU2ZQ([FHSWLRQ&ODVVHV 2EMHFW 7KURZDEOH ([FHSWLRQ 5XQWLPH([FHSWLRQ « 7RR0DQ\3DVVHQJHUV([FHSWLRQ "!$#%"&"')(+* , (-./,'0'/ ("- .3/,"' -("1# 1$$""!"#2%&$' (3*, 3 !"#1 %$&'(3*,87 ,* "&2*"42 %&$' (3*,65 29$:""")"!$#$;<5 7 = >2#0#?*A@ ?2"2!""#"BB.2"# 4DCE= FG9:""22!"#"2;+H I I SAP AG 2004 You can also define your own exception classes. You must attach the class in the inheritance hierarchy of the exception classes. © SAP AG JA100 6-4 8VHIXO0HWKRGVIRU+DQGOLQJ([FHSWLRQV 2EMHFW 7KURZDEOH ([FHSWLRQ 5XQWLPH([FHSWLRQ « 7RR0DQ\3DVVHQJHUV([FHSWLRQ 7KURZDEOH SXEOLF6WULQJ JHW0HVVDJH SXEOLFYRLG SULQW6WDFN7UDFH SXEOLF6WULQJ WR6WULQJ SAP AG 2004 Since every exception class is ultimately derived from java.lang.Throwable, every exception object can use the methods listed above, which can be helpful for the exception handling: 1: Returns an error text as a string 2: Prints an excerpt from the runtime stack (call hierarchy) 3: Returns a short description of the exception object as a string © SAP AG JA100 6-5 ([FHSWLRQV 7KH EDVLF SULQFLSOHV RIH[FHSWLRQ KDQGOLQJ DUH z At program runtime, a runtime error or a condition set purposely by the programmer triggers an exception. z The exception can either be passed on by the program part in which it was triggered, or it can be handled. z If the exception is passed on, the recipient can either handle it himself or pass it on further. z If the exception is not handled in any program section, it causes program termination and an error message is issued. SAP AG 2004 © SAP AG JA100 6-6 7ULJJHULQJ ([FHSWLRQV ([SOLFLWO\ 8VHUGHILQHGH[FHSWLRQVDQGH[FHSWLRQVRIWKH -6'.FDQEHH[SOLFLWO\WULJJHUHGZLWKWKURZ ("-.K/,"'L'/1 2""!1#M5 (1#,N1*)O*"*,'L,$* ("-./,"' 9:"!"#1APRQKH $""!"#S7T;U5 29$:" "!$#"FFVH ,": 7W2 9":" "!1#"BXOY;R5 *)>"# J I $/" J 1 1"!""#$%2&' (3*,Z7[9$:$""!2#1;+H 5 \ 3*)@8]^ -3*_]`(1#,2*/ a7 =>",1,"G" "!2#cb2d]E= Fe2 91:2 "!1#;_H I I I SAP AG 2004 The throw statement explicitly triggers an exception. The syntax of the throw statement is: throw <exception object>. The exception object can already have been created, but it is usually created within the throw statement with QHZ. © SAP AG JA100 6-7 'HFODULQJ([FHSWLRQV 8VLQJWKHNH\ZRUGWKURZV\RXFDQGHFODUHH[FHSWLRQVDQG SDVVWKHPRQWRWKHFDOOLQJPHWKRG ("-.K/,"'L'/1 2""!1#M5 ($#,N"$*O*"*,'L,"* (-./,' I 9":"!"#1APfQKH 2""!"#S7T; *>2# J ) 3)"!"#1 %$&'(3*,g5 292:" "!2#2FFVH ,": 7h2 9:""!1#BX<Y;<5 *>"#J I $/2 J ) 3)"!"#1 %$&'(3*,879$:2"2!"#1;KH 5 \ *)@i]j-3*_]`($#,$*/ a7 =)>2,$G,"B"" "!$#Ab2k]E= FG$92:2 2!2#2;lH I I I SAP AG 2004 Use the keyword WKURZV to declare exceptions that can occur during the method execution. To do this, attach the keyword WKURZV to the end of the method header with a list of all the exceptions that should not be handled. In the case of an error, the exceptions specified are then forwarded to the calling method. © SAP AG JA100 6-8 +DQGOLQJ([FHSWLRQV 8VHWKHWU\FDWFK VWDWHPHQWWRKDQGOHH[FHSWLRQV WU\ 5 m"m?p u$|w{"opfq r$peo$qvqp +pu+qo<qrv1qG|vu m"mRqr"~2{LvuOp+|)pTDq)t{ uU"t2q r3t u?vfq~ x_y zw"{"| } I FDWFK B$"$',1*L"&'(+* ,e>"4$/ "#1AJ,1*>U 11"$ +"2L"$232)1 _;?5 FDWFK 7h2e* #.$/2'c.$G($# N2,4,!0?#@# 7"31 11)"22L1)31 2 " +) _)3;f5 m"m0voo"{2|tvqpLp | pkq t{uGr$vu$w"p~2oLt2q rOvfq~)x_yzw{1|} '1*'>./"'c4,"# "'$* /U:$*)"#?* > m"mBzxA_~2{2t2tu1{u"pL{~{ ~2pU|)vq |rBzw{1|}$oet ~2p"|$qw)x e*#.$/2' m"m0vs$q p~fq r$p<q~ x_y z1w"{"| } I I ¡ : LQDOO\ m"mUnop<q r$pes2tu$vww)x+y z1w"{"| }Oq {U|w"{opBs2tw"po 5 m"m?{~e~p"wpvo"pLox1o3qpR~p"o{n~2|po IB SAP AG 2004 The WU\ block contains one or more statements for which an exception can occur if they are executed. In case of an error, the normal program execution is interrupted and the program flow is continued with the first statement after the FDWFK clause that declared the relevant exception class. This means that exceptions and errors that occur during execution of the WU\ block do not lead to termination of the program. The FDWFK block can include the code for realizing an appropriate reaction to the error. If you use several FDWFK blocks, you must pay attention to their sequence because they are processed in the sequence in which they appear. The optional ILQDOO\ block closes the try/catch construct and contains statements that are to be executed, irrespective of the occurrence of an exception. © SAP AG JA100 6-9 +DQGOLQJ([FHSWLRQV([DPSOH (2-./,"'L'/ "2!$#2"*M5 (2-./,2'?*1* ,"'N2,4 *# @$2,¦7 \ *#", ! ¡T "#!3;f5 5 :# 7 ,2* ,4&LP<Q+HÄ,4&BÅÇÆHÄ,4&F2F2;f5 2""!2#A($AP "J 2")!2#D7^;KH I I '""* '> 7» 122"2!2#"%&$' (3*, L"&"';f5 * / Z7 =%$&' (3*,kÊ = ;KH \ *)@È]É-2*k]h(3#, *)@È]É-2*k]h(3#, * /Z 7»&1'Ë]`!"2*1 !a7É;";+H \ I I I "c402:A@2$, "c24G2:L'/"2 ¢3£"¤ ¥¦¤ ¥¦§¨)¥¥©ª«©¬1­K®1¯° ¢3£"¤ ¥¦¤ ¥¦§¨)¥¥©ª«©¬1­K®1¯ ± ¢3£"¤ ¥¦¤ ¥¦§¨)¥¥©ª«©¬1­K®1¯ ² ¢3£"¤ ¥¦¤ ¥¦§¨)¥¥©ª«©¬1­K®1¯³ ´µ¶)©· ¸`¤ ®1ª2¹ ¢3£©¬º©Z¨¬º©i¸»®"®½¼a¨ª¾¿§"¨¥¥ ©ª«©¬»¥Z®1ª½À®¨¬hÁ3Âà SAP AG 2004 In the example above, the critical IRUloop is embedded in a WU\ block. As soon as the fifth passenger is created, the constructor of the 3DVVHQJHUclass throws the exception TooManyPassengersException, which is then caught in the FDWFK block. © SAP AG JA100 6-10 &KHFNHG([FHSWLRQV &KHFNHGH[FHSWLRQVPXVWEHKDQGOHGRUGHFODUHG 7KURZDEOH 2EMHFW (UURU ([FHSWLRQ 2 « « « « « « G>1,Ì(#!$# @f' 8ÍÉ*Î.?' @(1,"/ "4 ("- .3/,"'L'/1 Ï>1' 4%2&'(_*,g5 (1-./,2'L* 1* ,"'N2, 4 , 2* @$2,¦7 \ *#,! ¡T 2#!$2;f5 ,4&VH , 4&eP \ *@a]É,k]T# 2487T;H \ "*@8]^ -1*d]W(K#,2*/ a7[,42&$;lH I I 'XULQJ FRPSLOLQJ Ð £© ¶Ñ ©Á1´µ¶)©· ¸`¤ ®1ª¯ ÒW¨Ó¨"´µ¶)©·¸`¤ ®1ªÔÒW¨ Ó¨¯Õ¤ ®1¯×Ö ØÔ´µ¶)©·¸É¤ ®1ªa¼ÚÙ¥¸3À© ¶¨Ù«1£ ¸[Û)®¬1¤ ¸¼ÜÙ ¥¸3À ©DÁ©¶Ý ¨¬W©Áڤתi¸É£©D¸`£"¬h®ÞD¥Z¶Ý ¨Ù ¥©È®ß"¸[£"¤ ¥È¼a©¸`£®"Á1¯ ¤ ÁµÈàÈá"¾ ¥ ¸h©¼Ü¯Õ¤×ª"¯×¬h©)¨ Á$âºã`ä SAP AG 2004 Controlled exceptions must either be caught using WU\FDWFK, or be passed on to the calling methods using WKURZV in the method header. © SAP AG JA100 6-11 +DQGOLQJD&KHFNHG ([FHSWLRQ +DQGOLQJ ("-)./,"'L'/ 3 Ï>2'4 %2&'(+* ,å5 (1- .3/,'U*1*,'GN,4 ,3* , 4"&kH *# 5 @12, a7 \ *#,! ¡ #!12;f5 ,4"&eP \ K*@8]T,D]# 4a7;_H / i7h,4&3;+H \ K*@Z]-$*_](#,* X ' 1* '> I 7Éæ NV],k]ç9%&'(K*,?, %2#"#2;f5 \ K*@Z]-$*_](#,* /i7 ="ç)9e%1###= ;+H I I I (2-./,2'è]]]é,"*G#4i7É;*>"#Jê"ë ì"íî2ïV SAP AG 2004 A FDWFK block catches the exceptions that are assignment-compatible to the type of declared variables. This includes the specified exception class and all its subclasses. … catch (Exception H[F) {...} This catch block handles all exceptions, since ([FHSWLRQ is the superclass of all the exception classes. When the exception is triggered, an instance of the relevant exception class is created at the same time. To this is passed the handling FDWFK block as an object reference. Within a FDWFK block are the statements that should be executed when an exception occurs during the execution of the WU\ block. The error can be resolved in the FDWFK block, or detailed error information can be output. This should be performed with the standard error output System.err. © SAP AG JA100 6-12 'HFODULQJD&KHFNHG([FHSWLRQ 'HFODULQJ ,@(3#1* W 90 æ N$d]T,Ô]Tç9 %2&' (*, "ðH ("-./,2'0'/ Ï>1' 4%2&"'(_*,g5 (-.K/,'U* $* ,2'BN,4 , * @2$,a7 \ *#,! ¡T #!$2 W; *>1#J ç9"%&$' (*, g5 , 42&ðH , 4"&eP \ K*)@i]T,8]É#4È7;lH W 3*/i7[,4&;H \ K* )@a]`-$*l](#", I I public ... int #4 () throws ê"ë ì"íî2ïV SAP AG 2004 In the above example, the UHDG method is called from the PDLQ method, whereby the declaration of the UHDG method contains the extension “throws java.io.IOException”. Since the PDLQ method does not handle this exception using a WU\FDWFK, it is declared again by WKURZVin the definition of the PDLQ method after the parameter list. In this way, it is passed to the calling position. In this particular case, this is the virtual machine (VM), which terminates the program when an exception occurs and issues an error message with StackTrace. © SAP AG JA100 6-13 8QFKHFNHG([FHSWLRQV ,IXQFKHFNHGH[FHSWLRQVDUHQRWKDQGOHGWKH\DUHDXWRPDWLFDOO\ IRUZDUGHGWRWKHFDOOHU `T 2EMHFW (2-./,2'e'/ 7KURZDEOH « « ([FHSWLRQ « « 5XQWLPH([FHSWLRQ « 3 ñ3,)NKòf5 (-)./,'U*)*,"'N",4 ,$* (UURU @22,a7 \ *#,! ¡ #!2$;R5 N$/kóô42, N1,"#kH 4,N",1$#BPfQ_H N2/PRò Q"QL4$,)N,#kH $W UXQWLPH \ K*@a]`-1*ð]»(1#",3* /Z7»N/;H I Òh¨Ó¨¯×Ý ¨ª«1¯ õd¬[¤ ¸`£¼a©)¸É¤ ¶´µ¶)©·¸É¤ ®1ª$Âö2À)¾Z÷©¬W® I ¨¸3øl¤ Ó°)¯ ¼a¨¤×ªâ»øl¤ Ó°)¯ Òh¨Ó"¨Âúùã ´µ¶©· ¸`¤ ®1ª½¤×ªZ¸`£"¬W©¨ Áüû ¼a¨¤×ªý SAP AG 2004 Unchecked exceptions (RuntimeExceptions) can also be caught usingWU\FDWFK, just like checked exceptions. If this does not happen, then (in contrast to checked exceptions) they are automatically forwarded to the caller. The caller can then handle the exception, or it is automatically forwarded again. If the exception is not handled anywhere, the program terminates. © SAP AG JA100 6-14 $YRLGLQJ+DQGOLQJ8QFKHFNHG([FHSWLRQV 8QFKHFNHG H[FHSWLRQVFDQEHDYRLGHGE\PHDQVRIFKHFNV RUFDQEHKDQGOHG $YRLGLQJ ,: 7W4$,N1,")$#BPPfQ2; 5 \ *))@a]`-$*d]h(#,$*/i7 =Î.2Oÿ #dÊ= ;lH $/" I 5 N$/P ò Q"QLc4,N2,#kH \ *))@a]`-$*d]h(#,$*/i7»N2/$;_H I +DQGOLQJ * #) 5 N2/cPfò"QQLc4$, N,2#ËH I '"*'> 7úþ#,1*>@2* ,"'%&1'(3*,G$#,%"#"#2;R5 \ K* @8]T-3*l](1#","*/a7 = þ#","*>@"* ,"'%2##"#ÔÊT= ;+H \ K* @8]T-3*l](1#","*/a7h2#,%2##V]!"2*$3"!a7É;";+H I SAP AG 2004 © SAP AG JA100 6-15 6XPPDU\ <RXVKRXOGQRZEHDEOHWR z ([SODLQWKHFRQFHSWRIH[FHSWLRQKDQGOLQJLQ-DYD z $YRLGSURJUDPWHUPLQDWLRQVWKURXJKDSSURSULDWH HUURU KDQGOLQJ z &UHDWH\RXURZQH[FHSWLRQFODVVHV SAP AG 2004 © SAP AG JA100 6-16 ([HUFLVH 8QLW ([FHSWLRQV 7RSLF 8QFKHFNHG([FHSWLRQV At the conclusion of this exercise, you will be able to: • Catch and handle an exception of the type unchecked exception, which occurs during program execution 6DPSOHVROXWLRQ: 3URMHFW 6WDUW8S.LW 3DFNDJH FRPVDSWUDLQLQJH[FHSWLRQVVRO 1-1 1-2 In your project 0\3URMHFW, create a new package with the name FRPVDSWUDLQLQJH[FHSWLRQVH[F. In this package, define the class &DU in line with the class diagram shown below. The constructor of this class should accept values for the two attributes and transfer them into the attributes. In your package FRPVDSWUDLQLQJH[FHSWLRQVH[Fcreate the class 8QFKHFNHG([FHSWLRQ7HVW. Let the wizard create a PDLQmethod for you. Within this PDLQ method, define an array of the type of the class &DU with a length of . In position 10 of this array, add the reference to a &DU object. 1-3 Since the last valid array entry has the index position 9 (= array length - 1), the runtime system triggers the exception $UUD\,QGH[2XW2I%RXQGV([FHSWLRQ when your application is executed. Catch this exception using a WU\FDWFK construction. 1-4 Test your application. © SAP AG JA100 6-17 © SAP AG JA100 6-18 6ROXWLRQ 8QLW ([FHSWLRQV 7RSLF 8QFKHFNHG([FHSWLRQV SXEOLF FODVV Car { SULYDWH LQW seats; SULYDWH String make; SXEOLF Car(LQW seats, String make) { WKLV.seats = seats; WKLV.make = make; } } SXEOLF FODVV UncheckedExceptionTest { SXEOLF VWDWLF YRLG main(String[] args) { Car[] carFactory = QHZ Car[10]; WU\ { carFactory[10] = QHZ Car(5, "Mercedes"); } FDWFK (ArrayIndexOutOfBoundsException e) { System.out.println(e.toString()); } System.out.println("test"); } } © SAP AG JA100 6-19 © SAP AG JA100 6-20 ([HUFLVH 8QLW ([FHSWLRQV 7RSLF &KHFNHG([FHSWLRQV At the conclusion of this exercise, you will be able to: • Define your own exception classes • Trigger exceptions using the WKURZ statement in the program • Declare exceptions in method interfaces • Catch and handle an exception of the type checked exception, which occurs during program execution 6DPSOHVROXWLRQ: 3URMHFW 6WDUW8S.LW 3DFNDJH FRPVDSWUDLQLQJH[FHSWLRQVVRO 3UHOLPLQDU\FRQVLGHUDWLRQV It should only be possible to create &DU objects with two to eight seats. If a number of seats outside this range is selected in the instancing, then a user-defined exception is triggered. 2-1 To apply the scenario described, create the exception class ,QYDOLG1XPEHU2I6HDWV in the package FRPVDSWUDLQLQJH[FHSWLRQVH[F. It should be derived from ([FHSWLRQ and should have a constructor through whose interface the invalid number of seats can be passed. In the implementation of this constructor, call the superclass constructor and pass to it an informative exception text based on the invalid number of seats. This text can later be queried in the exception handling using the method JHW0HVVDJH © SAP AG JA100 6-21 2-2 2-3 2-4 Adapt the constructor in your &DU class. Again supply the value passed through the interface to the manufacturer attribute. Check whether the value passed for the number of seats is between two and eight. If this is the case, transfer this value into the relevant attribute. Otherwise, trigger an exception of the type of the exception class defined in step 2-1. Pass the invalid number of seats to the constructor of the exception class. The triggered exception should not be handled locally in the &DU constructor, but should be passed on to the caller. Declare the exception in the constructor interface. In your package FRPVDSWUDLQLQJH[FHSWLRQVH[F,create the class &KHFNHG([FHSWLRQ7HVW for testing. Let the wizard create a PDLQmethod for you. Within this PDLQmethod, define an array of the type of the class &DU with a length of . Fill this array with references to &DU objects. All the &DU objects created should have the same manufacturer and should only differ in the number of seats. The referenced &DU object in position L of the array should have L seats. For this, implement a IRU loop. 2-5 Use the WU\FDWFK construct to catch and handle the checked exception passed on by the &DU constructor within the IRU loop. 2-6 Test your application. © SAP AG JA100 6-22 6ROXWLRQ 8QLW ([FHSWLRQV 7RSLF &KHFNHG([FHSWLRQV SXEOLF FODVV InvalidNumberOfSeats H[WHQGV Exception { SXEOLF InvalidNumberOfSeats(LQW seats) { VXSHU("Invalid number of seats: " + seats); } } SXEOLF FODVV Car { SULYDWH LQW seats; SULYDWH String make; SXEOLF Car(LQW seats, String make) WKURZV,QYDOLG1XPEHU2I6HDWV { WKLV.make = make; LI VHDWV! VHDWV ^ WKLV.seats = seats; } `HOVH^ WKURZQHZ,QYDOLG1XPEHU2I6HDWV VHDWV ` } SXEOLF FODVV CheckedExceptionTest { SXEOLF VWDWLF YRLG main(String[] args) { Car[] carFactory = QHZ Car[10]; IRU (LQW i = 0; i < carFactory.length; i++) { WU\ { carFactory[i] = QHZ Car(i, "Mercedes"); © SAP AG JA100 6-23 System.out.println("Car with " + i + " seats constructed."); } FDWFK (InvalidNumberOfSeats e) { System.out.println(e.getMessage()); } } } } © SAP AG JA100 6-24 ([HUFLVH 2SWLRQDO 8QLW ([FHSWLRQV 7RSLF &KHFNHG([FHSWLRQV At the conclusion of this exercise, you will be able to: • Use additional attributes and methods in self-defined exception classes 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJH[FHSWLRQVVRO 3UHOLPLQDU\FRQVLGHUDWLRQV If an exception of the type ,QYDOLG1XPEHU2I6HDWV is triggered when a &DU object is instanced, then the handler of this exception should get access to the manufacturer of the car affected. For this, the exception class is expanded. © SAP AG JA100 6-25 3-1 3-2 Expand the exception class ,QYDOLG1XPEHU2I6HDWV in the package FRPVDSWUDLQLQJH[FHSWLRQVH[F in line with the class diagram shown. Thus, you create an attribute for storing the manufacturer in the exception instance together with the related JHW method. You also define an additional constructor by means of which the invalid number of seats and the related car manufacturer can be transferred. Call up the existing constructor from the implementation of this constructor and pass the number of seats to it. Supply the value of the related interface parameter to the manufacturer attribute. Adapt the constructor in your &DU class. To trigger the exception there, use the constructor of the exception class created in step 3-1 to store the manufacturer in the exception instance. 3-3 In the exception handling, access the additional information stored in the exception object. For this, switch to your test class &KHFNHG([FHSWLRQ7HVW and adapt the FDWFK block in the PDLQ method appropriately. In this block, call the method JHW0DNH for the exception object and output the returned car manufacturer on the console. 3-4 Test your application. © SAP AG JA100 6-26 6ROXWLRQ 2SWLRQDO 8QLW ([FHSWLRQV 7RSLF &KHFNHG([FHSWLRQV SXEOLF FODVV InvalidNumberOfSeats H[WHQGV Exception { SULYDWH6WULQJPDNH SXEOLF InvalidNumberOfSeats(LQW seats) { VXSHU("Invalid number of seats: " + seats); } } SXEOLF,QYDOLG1XPEHU2I6HDWV LQWVHDWV6WULQJPDNH ^ WKLV VHDWV WKLVPDNH PDNH ` SXEOLF6WULQJJHW0DNH UHWXUQPDNH ` ^ SXEOLF FODVV Car { SULYDWH LQW seats; SULYDWH String make; SXEOLF Car(LQW seats, String make) WKURZV InvalidNumberOfSeats { WKLV.make = make; LI (seats >= 2 && seats <= 8) { WKLV.seats = seats; } HOVH { WKURZ QHZ,QYDOLG1XPEHU2I6HDWV VHDWVPDNH } } } © SAP AG JA100 6-27 SXEOLF FODVV CheckedExceptionTest { SXEOLF VWDWLF YRLG main(String [] args) { Car[] carFactory = QHZ Car [10]; IRU (LQW i = 0; i < carFactory.length; i++) { WU\ { carFactory [i] = QHZ Car(i, "Mercedes"); System.out.println("Car with " + i + " seats constructed."); } FDWFK (InvalidNumberOfSeats e) { 6\VWHPRXWSULQWOQ HJHW0HVVDJH 0DNH HJHW0DNH } } } } © SAP AG JA100 6-28 ,QWURGXFWLRQ WR-DYD&ROOHFWLRQV )UDPHZRUN &RQWHQWV z '\QDPLF GDWD FRQWDLQHU z %DVLFFRQWDLQHUW\SHV/LVW6HWDQG0DS z ,PSRUWDQWFODVVHVDQGLQWHUIDFHVRIWKH-DYD&ROOHFWLRQV )UDPHZRUN z 6RUWLQJ FRQWDLQHU FRQWHQWV SAP AG 2004 © SAP AG JA100 7-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z 'HVFULEHWKHVWUXFWXUHRIWKH-DYD&ROOHFWLRQV)UDPHZRUN z 8VHWKHPRVWLPSRUWDQWFODVVHVDQGLQWHUIDFHVRIWKH -DYD&ROOHFWLRQV)UDPHZRUN z 6RUWWKHFRQWHQWVRIGDWDFRQWDLQHUV z 2YHUZULWHWKHHTXDOV PHWKRGLQ\RXURZQFODVVHV z 2YHUZULWHWKHKDVK&RGH PHWKRGLQ\RXURZQFODVVHV SAP AG 2004 © SAP AG JA100 7-2 %DVLFV 'DWD 6WUXFWXUHV'DWD &RQWDLQHUV 0DQXIDFWXUHU 0RGHO $VVLJQHG" &DU /LFHQVH QXPEHU 6XQURRI" &RORU 'DWD &DU &DU &DU &DU &DU 2EMHFWV &RQWDLQHU 2EMHFWV SAP AG 2004 Data is encapsulated in objects through object-oriented programming. In this way, data can be used and modified using structured objects. Objects, in turn, are also used to organize other objects. These objects are generally referred to as FRQWDLQHUV. The Java Collections Framework supplies generic containers, that is, containers which: y Can contain different types of objects; the collection implementations (classes) work with the shared superclass for all classes: java.lang.Object y Can contain any number of objects, meaning that they can have a dynamic size © SAP AG JA100 7-3 7KUHH%DVLF7\SHVRI&RQWDLQHUV /LVW • &RQWDLQHUVIRUREMHFWVWKDWVKRXOGEH DFFHVVHGVHTXHQWLDOO\RUUDQGRPO\ • 'XSOLFDWHV DUH DOORZHG • ,QVHUWLRQVHTXHQFH LV NHSW 6HW • &RQWDLQHUVIRUDTXDQWLW\RIREMHFWVLQWKH PDWKHPDWLFDOVHQVH • 1RGXSOLFDWHV • ,QVHUWLRQVHTXHQFHLVQRWNHSW .H\9DOXH 3DLUV • &RQWDLQHUVIRUUHODWHGREMHFWSDLUV SAP AG 2004 The three basic container types are described by individual interfaces in the Collections Framework. For each interface there are several classes that implement the interface. The term GXSOLFDWH is defined in the Collections Framework as: an object o1 is the duplicate of the object o2, if o1.equals(o2) returns the value “true”. © SAP AG JA100 7-4 2YHUYLHZ&ROOHFWLRQ )UDPHZRUN &RPSDUDEOH &RPSDUDEOH &ROOHFWLRQ &ROOHFWLRQ ! ! ! ! ! 6RUWHG6HW 6RUWHG6HW $EVWUDFW $EVWUDFW &ROOHFWLRQ &ROOHFWLRQ $EVWUDFW6HW $EVWUDFW6HW $EVWUDFW/LVW $EVWUDFW/LVW 7UHH6HW 7UHH6HW +DVK6HW +DVK6HW $UUD\/LVW $UUD\/LVW (QXPHUDWLRQ (QXPHUDWLRQ 0DS 0DS ! /LVW /LVW 6HW 6HW ! ! ! 6RUWHG0DS 6RUWHG0DS 0DS(QWU\ 0DS(QWU\ $EVWUDFW $EVWUDFW 0DS 0DS &ROOHFWLRQV &ROOHFWLRQV +DVK0DS +DVK0DS ! ! 7UHH0DS 7UHH0DS :HDN+DVK :HDN+DVK 0DS 0DS ,WHUDWRU ,WHUDWRU ! ! ! /LVW,WHUDWRU /LVW,WHUDWRU 'LFWLRQDU\ 'LFWLRQDU\ $EVWUDFW $EVWUDFW 6HTXHQWLDO/LVW 6HTXHQWLDO/LVW 9HFWRU 9HFWRU +DVKWDEOH +DVKWDEOH /LQNHG/LVW /LQNHG/LVW 6WDFN 6WDFN 3URSHUWLHV 3URSHUWLHV SAP AG 2004 For managing and editing larger data quantities, you already have the classes Stack, Hashtable, Vector, and BitSet in the java.util package. As of JDK 1.2, further container classes have been provided through the Collection concept. However, the old classes have been retained and integrated into the new concept. © SAP AG JA100 7-5 ,QWHUIDFHMDYDXWLO&ROOHFWLRQ &ROOHFWLRQ *URXSRIREMHFWV 3RVVLEO\ VRUWHG 3RVVLEOH GXSOLFDWHV 'HULYDWLRQMDYDXWLO6HW XQRUGHUHGQRGXSOLFDWHV 'HULYDWLRQMDYDXWLO/LVW RUGHUHGGXSOLFDWHV SAP AG 2004 The Collection Interface provides a basis interface from which most interfaces are derived. It groups the common features of different container classes together. A Collection does not specify whether the objects are kept in a certain sequence or whether duplicates exist. A Collection is seldom implemented directly. Instead, the sub-interfaces List and Set are used. y List: Ordered Collection; duplicates are possible y Set: Unordered Collection; duplicates are not possible © SAP AG JA100 7-6 ,QWHUIDFHMDYDXWLO/LVW !"# ! ! ! &ROOHFWLRQ &ROOHFWLRQ ! ! ! /LVW /LVW $&%'%)(!*,+.- /0 13254!0768% )RUFRQWDLQHUVZKRVHFRQWHQWVKRXOGEHDFFHVVHG VHTXHQWLDOO\RUUDQGRPO\ 'XSOLFDWHV DUH DOORZHG 7KHVHTXHQFHLQZKLFKWKHREMHFWVDUHDGGHGLVNHSW SAP AG 2004 Classes that implement the List interface represent a list that can contain duplicates, and to which ordered access is possible through an index. The index begins with 0. The last element has index size ()-1. During runtime, elements can be deleted from or inserted into the list. A considerable advantage of lists over arrays is that the size of the list can be adapted dynamically. In addition to the methods inherited by the Collection interface, other methods are also available for access. For inserting elements at a certain position, there are the methods add and addAll with an extended parameter list. The return value of the add methods is “true” if the list has changed, that is, if elements were added. However, the add method returns “false” if the list has not changed. © SAP AG JA100 7-7 MDYDXWLO9HFWRU "!9 :; ! ! /LVW /LVW 2EMHFW $EVWUDFW/LVW $EVWUDFW&ROOHFWLRQ 9HFWRU 'XSOLFDWHV DUH DOORZHG *URZV DQGVKULQNV G\QDPLFDOO\ $FFHVVPHWKRGVDUHGHFODUHGDVV\QFKURQL]HG Delete Delete 9HFWRU Replace < (=%C>.D Read Read < (=%=>@? < (=%=>B < (=%=>@A Add Add E FHG#I SAP AG 2004 The class 9HFWRU from the package java.util is the Java representation of a linear list. The list can contain elements of any type, and their length can be changed during runtime. 9HFWRU allows you to add elements in any place and allows you to access the elements both sequentially and randomly. The J2SDK realizes a vector as an array of elements of the type REMHFW. Thus, accessing existing elements and running the list are fast operations. Deletions and additions that exceed the internal capacity of the array are, in contrast, relatively slow, because parts of the array have to be copied in. In Java, threads are integrated directly into the language as a structure for enabling concurrence. This means that a thread is an independent program fragment that can run parallel to other threads. The communication of two threads is enabled by the basis of shared variables, which can be reached by both threads. If both processes carry out changes on the shared data, they have to be synchronized because otherwise there could be undefined results. The keyword V\QFKURQL]HG is used to synchronize parallel processes. With V\QFKURQL]HGyou can identify either a complete method or a block within a method as a basic program fragment. This means that identifying a method as synchronized ensures, for example, that the complete code within the method is executed without an interruption by another thread. © SAP AG JA100 7-8 MDYDXWLO$UUD\/LVW "!" :; " ! ! /LVW /LVW 2EMHFW $EVWUDFW&ROOHFWLRQ $EVWUDFW/LVW $&%9%)(*K+K- /0 $UUD\/LVW URXJKO\FRUUHVSRQGVWRWKHFODVV9HFWRU 0DLQGLIIHUHQFH 7KHDFFHVVPHWKRGVRI$UUD\/LVW DUHQRWV\QFKURQL]HG $&%%J(*K+K- /0 < (,%C>KD < (C%,>@? < (C%,>B < (=%,>5A E FHG#I SAP AG 2004 ArrayList is a very commonly used list container which, like 9HFWRU, uses an array internally. As with 9HFWRU, the size of the container objects is also managed dynamically. © SAP AG JA100 7-9 ,QWHUIDFHMDYDXWLO,WHUDWRU )RUUXQQLQJWKURXJKDFROOHFWLRQ VHTXHQWLDOO\ ,WHUDWRU %RROHDQ KDV1H[W 2EMHFW QH[W YRLG UHPRYH ,WHUDWRU! V V V R Z[ V V V R SU LMYN L M N LM7N LM7N V RZ [ V#W MX N RTS U OP Q O PQ O!P Q OP Q R'Z [ R SU R SU R SU V V P P P P P R Z[ O!P Q < (=%=>KD LM7N < (C%,>@? < (,%C>B < (=%,>5A R SU \ PQ R SU R SU \ PQ \ PQ R SU E FHG I \ PQ SAP AG 2006 The Iterator interface provides a standard for running the different data containers. Using the Iterator interface, you run through the container sequentially, but not randomly. This means that you read forward only and you cannot skip any elements. Using the hasNext() method, you can check whether you have reached the last element in the container. Using the next() method, you can access the next object of the collection. The remove() method removes the element from the Collection that was last returned by the Iterator. © SAP AG JA100 7-10 ([DPSOH/LVWVDQG,WHUDWRUV ]^C_3`=acb d!e5fcehgi8bC]=jkglnm _,iopjC]Kqrq@j@etsCs u.v^3`xw _.iCocjC]KqysCb@e.b=]@qzf,`.]@{ v,q.b5`.azf=v=q8b`ca ^3eC],|~}",b@aK]5|Ke.a53s=w ©,2072C% |Cv, ©,(=ªK« v=qcb`.a}Tm ©,(=ªK« ¬~(C%- 68­ f=v,q.b5`.a&gTe@{@{} vtbvca3 m f=v,q.b5`.a&gTe@{@{} 5e=iKj m f=v,q.b5`.a&gTe@{@{} 5e=iKj m f=v,q.b5`.a&gTe@{@{} ce.aC],`@| m @`=a } ]5|tb ]nm]fcv=qcb`.a&g s5],@v~}Tm],=.w Cb@aK]5|K|Ce^tv}.baK]@|Cpf.v=q8b`Kahg"Kv.b~}Y]3m 3s,bv@^g`i8bhgY_paC]=|Kb,j| }Y|=e5^.vppm ¡ ©,2072C% f=v,q.b5`.a&ga5v!^p`5fcv~}¢,m ©,(=ªK« £ bv.aCe8b`.a]8bv8af=vcq,b`cang],b@v,a,e.b`ca¤}Tm C¥K],j@v ©,(=ªK« }"],b!v8a&g9¥Kets ¦tvC§tbk}9.w Cb@aK]5|K|Ce^tv}.baK]@|Cp]=bCv,a¨g9|CvK§.b~}"nm 3s,bv@^g`i8bhgY_paC]=|Kb,j| }Y|=e5^.vppm ¡ ¡ ¡ SAP AG 2004 © SAP AG JA100 7-11 ,QWHUIDFHMDYDXWLO6HW "9 ! ! &ROOHFWLRQ &ROOHFWLRQ ! 6HW 6HW ! ! 6RUWHG6HW 6RUWHG6HW ®t%J22¯820 1RGXSOLFDWHV 1RVSHFLILHG VHTXHQFH $FFHVVWKURXJK LWHUDWRUV SAP AG 2004 The Set interface is a pure marker interface because it does not define any additional methods; it differs from Collection only with regard to the description of the expected functions. Sets contain no duplicates. Two objects, obj1 and obj2, are duplicates if the test obj1.equals(obj2) gives the value “ true” . If you try to add a duplicate to the set, the method add then returns the value “ false” . The object is not added. You use iterator objects to access the elements of sets. The object elements in sets do not have a defined sequence. © SAP AG JA100 7-12 MDYDXWLO7UHH6HW "!" :; " ! !! ! ! 6RUWHG6HW 6RUWHG6HW 6HW 6HW 2EMHFW $EVWUDFW&ROOHFWLRQ $EVWUDFW6HW 7UHH6HW 2UGHUHGVHW VRUWHGLWHUDWLQJWKURXJKWKHHOHPHQWVSRVVLEOH 7UHH6HW < (=%=>KD < (=%=>@? < (=%C>5B < (=%=>@A E FHG I SAP AG 2004 TreeSet stands for an ordered Set implementation. The sequence in which you enter the elements into the Set does not have any effect on the order of the Set during read. © SAP AG JA100 7-13 ([DPSOH6HWV ]!^@_p`Cacb de@fce&g'i.b=]Cjkg £ bv=aKe,bC`=a¨m ]!^@_p`Cacb de@fce&g'i.b=]Cjkg°Ka@v@v3!vtbHm _.ioj@]KqqCjCets@s ucv^3`xw _.iopj@].q±sCbe8b5]Kqzf=`.]@{ ^ce.]|},b@aK]5|C²³eKa@3s=w °=a5vKv.@vKbrb5a=vCvtvtb´ |@v@ °Ka@vKvKCvKbk}Tm b@a5vKv.@vKb¨g9e@{K{µ} =vcb5v,aH m ¬¤(=%- 68­ b@a5vKv.@vKb¨g9e@{K{µ} ,e@icj3 pm ©=(=ª.« b@a5vKv.@vKb¨g9e@{K{µ} ,e@icj3 pm ©=20Y2,% b@a5vKv.@vKb¨g9e@{K{µ} pe,a,]@`K|p m £ bvca@e8b`caz]cbvcazb5a,v@v.@v.bhg'].bv8a5eKbC`,aµ}m =¥K]Kj5v }9],bvca&g¥,ets ¦8vC§3b¨}9Kw CbaK]@|,r|=e^3v}"Kb5aK]5|@pz],b@v,akg"|Cv,§cb~}9m 8s,bv5^µgT`5i.b¨gJ_pa=]=|.b=j5| }J|=e^cvpm ¡ ¡ ¡ SAP AG 2004 The sorting of the elements of a TreeSet container can be defined in two different ways: y Sorting by natural order: This means that the class whose objects are added to the container implements the Comparable interface. An order of the objects in the class is defined using the method compareTo, which is contained in the interface. y Random sorting: Here, an object whose class implemented the Comparable interface is passed to the constructor of TreeSet. Thus any natural order defined on the elements of the TreeSet is overridden. In the above example, string objects are added to the TreeSet container. For this, the natural order defined on strings is used, which means that the 6WULQJ class implements the Comparable interface. This interface is used to define a lexicographical order on character strings in the 6WULQJ class. As already mentioned above, a Set container cannot accept duplicates, whereby duplicates are identified by the HTXDOV method. The HTXDOV method is implemented in the 6WULQJ class in such a way that when it compares two character strings it returns “ true” if these two character strings have the same content. Thus, in the example, the name “ Paul” is only accepted into the container once. © SAP AG JA100 7-14 ,QWHUIDFHMDYDODQJ&RPSDUDEOH &RPSDUDEOH SXEOLF LQW FRPSDUH7R 2EMHFW R 6RUW E\ QDWXUDO RUGHU 7KHHOHPHQWVRID6HWDQG0DSFDQEHVRUWHGLI\RXLPSOHPHQWWKH &RPSDUDEOHLQWHUIDFHDQGGHILQHWKHFRPSDUH7R PHWKRGLW FRQWDLQVDVIROORZV 5HWXUQYDOXH7KHFXUUHQWHOHPHQWLVEHIRUH WKH HOHPHQW WR EH FRPSDUHG 5HWXUQYDOXH!7KHFXUUHQWHOHPHQWLVDIWHU WKH HOHPHQW WREH FRPSDUHG 5HWXUQYDOXH 7KHFXUUHQWHOHPHQWDQGWKHHOHPHQW WREHFRPSDUHGDUHWKHVDPH SAP AG 2004 In the above example, the iterators of the Set and Map containers have not returned the elements in a particular sequence, which means that these Collections – in contrast to List – are not sorted. The J2SDK also provides the option of sorting the elements of a Set or Map. For this purpose, you can: y Use the natural order of the elements y Sort the elements using an explicit compare object To sort by natural order, you must implement the Comparable interface in line with the above semantics. The natural order of instances of the class 6WULQJ, for example, is an ascending, lexicographical sort order. © SAP AG JA100 7-15 6RUWLQJE\1DWXUDO2UGHU ¶· ¸C¹º »»¹¼½!½ ¾·5½¿ ÀÁ5Âà ºTÁ5¶@¹ ÂÁ@ÂÄ¿½ ¾ÀÁ¶5¼Ã!¼¸C¹ ÂÅ ¶CÃ!ºÆ¼¿  ǿ ú ÄÈÉļÁÂtÊ ¶CÃ!ºÆ¼¿ º Ä@¿ º ËÊ ¶5· ¸@¹º » Õ ¾ ·@½!¿ÀÁ5Â5ÃÌJÇ¿Ã!º ÄÈÍÄ5¼Á5ÂtÎ ¿Ñº!½ Ò7ļÁ5ÂÔÓÍÄ!¼ Á5ÂtÊ ¿Ñº!½ Òº ËÔÓº Ë8Ê ¶5· ¸@¹º »Éº Ä5¿ ÈÂ5¿5ÖËHÌÏ×Å ÃÂ5¿·ÃÄ º Ë8Ê Õ ¶5· ¸@¹º » Õ Ç!¿ ú ÄÈÈÂ5¿TØ5¼Á5ÂHÌÏÅ ÃÂ5¿·ÃÄ Ä!¼Á@ÂtÊ º Ä¿ ºË5ÏÐÅ 1DWXUDO RUGHU $VFHQGLQJVRUWRUGHUEDVHGRQ FXVWRPHULG ¶5· ¸@¹º »Éº Ä5¿ »ÀÁ¶5¼ÃÂÙÀÌ Ú ¸,Û»¿ÜÀ¿ÑÂÃ!¾·5½¿ ÀÁ5Â!ÃÏÅ ÃÂ5¿·ÃĿѺ½ Ò7º ËÞÝÌÌ ¾·@½¿ À Á5ÂÃ@ÏßÀ¿ÑÂ5þ·5½¿ ÀÁ5ÂÃ@Ï8Ò7È¿!ÖËÌÏ=Ê Õ Õ SAP AG 2004 © SAP AG JA100 7-16 6RUWLQJE\1DWXUDO2UGHU ºÁ¶@Àÿ ºÁ¶@Àÿ Û¼ Æ!¼pÒJ·5¿º¹tÒÖ ¿Âü5¿À5ÃcÊ Û¼ Æ!¼pÒJ·5¿º¹tÒÙÃÂÂÇ¿tÊ ¶· ¸C¹º »»¹¼½!½ à@ÂÁ@À´Å ¶5· ¸@¹º »á½¿ ¼5¿ º»Æ!À!ºË Á@¼!º ÄHÌÇ!¿ ú ÄÈâ"ãܼ!à È5½!ÏÐÅ Ù!ÃÂÂÇ¿Ϳ ÃÂÂ!Ç Â=¿ßÓ ¿ ÃÂÂÇ¿cÒ7¼ Ë!ËHÌ ÄÂä ¿ ÃÂÂÇ¿cÒ7¼ Ë!ËHÌ ÄÂä ¿ ÃÂÂÇ¿cÒ7¼ Ë!ËHÌ ÄÂä ¿ ÃÂÂÇ¿cÒ7¼ Ë!ËHÌ ÄÂä ÄÂä ÙÃÂÂ!ÇÂ5¿tÌÏKÊ ¾·@½¿ ÀÁÂ!ÃnÌ åæC¼!º Â!Ã=å Îèç éêçÏÏ,Ê ¾·@½¿ ÀÁÂ!ÃnÌ åÇÁCº!¿ÑKå ÎßëìíçÏÏ,Ê ¾·@½¿ ÀÁÂ!ÃnÌ å'î!Â!» ïÂÃ@å Îñðò!êóÏÏ=Ê ¾·@½¿ ÀÁÂ!ÃnÌ åôCÈ!¼½½º5å Îõéë êçÏÏ=Ê D ?Aù B5úA!B úûA!B ûüý!B Ö¿Âü5¿ÀÃͺ¿ÂÃÓ׿ ÃÂÂÇ¿cÒ9º¿Âü¿ À!ÃÌ"ÏKÊ ä!Ѻ¹ Â Õ ÌJº¿ÂÃ3Ò)ѼC½'Ø5Âö@¿tÌÏÏ×Å ¾·5½¿ ÀÁ5Âû ·@½¿ À Á@Â!ÃÜÓ÷Ì#¾·5½¿ ÀÁÂ!Ã5Ïܺ¿ÂÃ3ÒYÄÂö@¿tÌÏ,Ê Çø@½¿ ÂÁÒYÀ·@¿.Ò ¶@Ã!ºÄ@¿ ¹ ÄHÌJ» ·@½¿À Á5ÂÃtÒYÈÂ5¿!ÖË&Ì7ÏÏ,Ê Õ Õ SAP AG 2004 © SAP AG JA100 7-17 ,QWHUIDFHMDYDXWLO&RPSDUDWRU &RPSDUDWRU LQW FRPSDUH 2EMHFW R2EMHFW R 2YHUZULWLQJ WKH QDWXUDO RUGHU 3DVVLQJDQREMHFWRIWKH&RPSDUDWRU W\SHWRWKHFRQVWUXFWRURIWKH &RQWDLQHU FODVV 5HWXUQYDOXH 5HWXUQYDOXH ! 5HWXUQYDOXH ºTÁ¶@ÀÃ5¿ RLV EHIRUH R RLV DIWHU R RDQGRDUH WKH VDPH Û ¼Æ!¼3Ò)·C¿º!¹tÒJ¾!ÀÁ!¶@¼Ã¼C¿ À!ÃcÊ ¶· ¸C¹º»Ô»!¹¼½½ ¾·@½!¿ÀÁÂÃØ5¼Á=¾ÀÁ¶5¼Ã!¼¿!Àà ºÁ¶@¹ ÂÁ5ÂÄ@¿½ ¾ÀÁ¶@¼Ã¼¿ ÀôŠ¶·¸C¹!º »ÍºÄ5¿ »ÀÁ¶C¼Ã ÂHÌ#Ú¸,Û»C¿þ» ·@½¿ ÀÁ5Â5ÃðKÎÚ ¸,Û»¿Ô» ·@½¿ ÀÁÂ!Ãò5ÏЊǿú ÄÈÍÄ!¼Á5ÂðÿÓÌÌ#¾ ·C½¿ÀÁ@ÂÃ5Ïÿ» ·@½!¿ÀÁ=Â!ÃðÏ.ÒJÈ¿TØ@¼ Á5ÂÌÏKÊ Ç¿Ãº ÄÈÍÄ!¼Á5ÂòÔÓÌÌ#¾ ·C½¿ÀÁ@ÂÃ5Ïÿ» ·@½!¿ÀÁ=Â!Ãò@Ï.ÒJÈ¿TØ@¼ Á5ÂÌÏKÊ Ã¿·Ã Ä Ä!¼Á5Âð8Ò7»ÀÁ¶@¼ÃÂ!ÙÀÌ)ļÁ5Â!òÏ,Ê $/54@2, ­ 8- ­ /C6c%#0c6t%,2,%@(/52 Õ 4@ª@/06 2,%c­@( 2 Õ 68­ SAP AG 2004 The Comparator interface is in the package java.util. It should be used for application-specific compares. The Comparator interface should be implemented by a third class that solely performs the compare. Comparator gives you the option of overriding the natural order. © SAP AG JA100 7-18 2YHUULGLQJWKH1DWXUDO2UGHU ºÁ¶@Àÿ ºÁ¶@Àÿ Û¼ Æ!¼pÒJ·5¿º¹tÒÖ ¿Âü5¿À5ÃcÊ Û¼ Æ!¼pÒJ·5¿º¹tÒÙÃÂÂÇ¿tÊ ¶· ¸C¹º »»¹¼½!½ à@ÂÁ@À´Å ¶5· ¸@¹º »á½¿ ¼5¿ º»Æ!À!ºË Ùà Â!ÂÇ Â5¿Í¿ à Â!ÂÇ Â,¿èÓ ¿ à Â!ÂÇ Â5¿8ÒY¼ËËÌ ÄÂä ¿ à Â!ÂÇ Â5¿8ÒY¼ËËÌ ÄÂä ¿ à Â!ÂÇ Â5¿8ÒY¼ËËÌ ÄÂä ¿ à Â!ÂÇ Â5¿8ÒY¼ËËÌ ÄÂä Á@¼!º ÄHÌÇ!¿ ú ÄÈâ"ãܼ!à È5½!ÏÐÅ Ä ä ÙÃÂÂÇ Â5¿pÌ ÄÂä ¾·@½¿ ÀÁ5Â!ÃØ,¼Á5Â!¾ÀÁ¶5¼!ü5¿ÀÃÌÏÏ,Ê ¾ ·C½¿ÀÁ@ÂÃ&Ì å"æ5¼!ºÂÃCå Î çéê!ç!ÏÏ,Ê ¾ ·C½¿ÀÁ@ÂÃ&Ì åÇTÁCº¿Ñ,å Îèëì!í ç!ÏÏ,Ê ¾ ·C½¿ÀÁ@ÂÃ&Ì åTîÂ!»ïÂ!ÃCå Îñð òêó!ÏÏ,Ê ¾ ·C½¿ÀÁ@ÂÃ&Ì åô5È!¼5½½ º@å Îõéëêç!ÏÏ,Ê Ö¿Âü¿ À!Ãͺ!¿ Â!ÃÓá¿ÃÂÂ!Ç Â@¿.Òº!¿Âü5¿ÀÃÌ9Ï=Ê äѺ!¹ Â Õ $ , (/5/,c254 2=% ¬~(=- 2=% ¯ õ - 0 ÌYº!¿ÂÃ3ÒYÑ!¼=½Ø5 öC¿3Ì7ÏÏÐÅ ¾·5½!¿ ÀÁ5Âû ·@½!¿ÀÁÂ!ÃÜÓ÷Ì#¾·@½¿ ÀÁÂ!Ã5Ïܺ¿ÂÃ3Ò7ÄÂö@¿tÌÏ,Ê Çø@½!¿ÂÁÒYÀ·@¿.Ò ¶CúĿ ¹ ÄHÌJ» ·@½¿ À Á@Â!ÃtÒYÈÂ5¿'Ø@¼ ÁÂHÌÏÏ,Ê Õ Õ SAP AG 2004 © SAP AG JA100 7-19 MDYDXWLO&ROOHFWLRQV6RUW <RXFDQVRUWOLVWVXVLQJWKHVWDWLFVRUW PHWKRGVRIWKH &ROOHFWLRQV FODVV 6RUWLQJWKHOLVWLQOLQH ZLWKWKHQDWXUDORUGHU RIWKHLUHOHPHQWV &ROOHFWLRQV static void sort(List list) static void sort(List list, Comparator c) 6RUWLQJWKHOLVWLQOLQH ZLWKWKHSDVVHG &RPSDUDWRUREMHFW SAP AG 2004 © SAP AG JA100 7-20 ,QWHUIDFHMDYDXWLO0DS " ! ! ! ! 0DS 0DS ! ! ! 6RUWHG0DS 6RUWHG0DS 3(/K¬( ®t%J22C¬~( 1RGHULYDWLRQ IURP MDYDXWLO&ROOHFWLRQ +ROGV NH\YDOXH SDLUV .H\V DUH DOZD\V XQLTXH $FFHVVYLDNH\V SAP AG 2004 A Map is a container for maintaining key value pairs. Each value object is saved together with a unique key object. This means that for each key object, there is exactly one value object, or no value object. You can compare a Map with the table of a relational database. Every entry in a map has a unique key, comparable to the primary key of a database table. If a new object is entered into the map and the object key already exists, the existing object is overwritten by the new object. You can read the value objects from the Map using your key. The Map interface is not derived from the Collection interface. The 7UHH0DS class is a Map implementation in which the entries are kept sorted on the basis of the keys. The key class must implement the Comparable interface (natural order), or the sorting is defined through an object that implements the Comparator interface. This object is transferred to the 7UHH0DS via the constructor. The second variant overrides any existing natural order of the key objects. © SAP AG JA100 7-21 MDYDXWLO+DVK0DS "!" :; " ! 0DS 0DS 3(/.¬¤( $EVWUDFW0DS 2EMHFW 0DSLPSOHPHQWDWLRQRQKDVKEDVLV • .H\YDOXHSDLUVDUHVWRUHGLQWKHPHPRU\LQEXFNHWV • 7KHEXFNHWEHORQJLQJWRDNH\YDOXHSDLULVVSHFLILHGE\WKHKDVK&RGH PHWKRGRIWKHNH\FODVV ! "T I ! W BB W B@ú B@ý E FG#I SAP AG 2004 W W On the basis of the hashCode() method of the key class, a Hash map calculates an internal position for every key value pair where this combination is to be included. These positions are also described as EXFNHWV. A bucket can: y Be empty (contain no object) y Contain exactly one key value pair (ideal case) y Contain a number of key value pairs When searching for a particular value object using its key, the following applies: If several key-value pairs are stored in a bucket, the system must compare the key objects in the bucket with the key of the object being searched for. © SAP AG JA100 7-22 MDYDXWLO0DS9LHZLQJ 0DS SXEOLF 6HWNH\6HW SXEOLF &ROOHFWLRQ YDOXHV 7KHNH\6HW PHWKRGUHWXUQVD6HW QRGXSOLFDWHV WKDWFRQVLVWVRI WKHPDSNH\V 7KHYDOXHV PHWKRGUHWXUQVD&ROOHFWLRQ GXSOLFDWHVSRVVLEOH WKDWFRQVLVWVRIWKHYDOXHV ZLWKRXWNH\V LQWKHPDS SAP AG 2004 © SAP AG JA100 7-23 +DVK0DS 8VDJH Û ¼Æ!¼3ÒJ·@¿º!¹tÒ$#¼½Ñ æ@¼¶nÊ Û ¼Æ!¼3ÒJ·@¿º!¹tÒ"Ö¿Â!ü¿ÀÃ8Ê Û ¼Æ!¼3ÒJ·@¿º!¹tÒ7Ç Â5¿KÊ ºÁ¶@À!ÿ ºÁ¶@À!ÿ ºÁ¶@À!ÿ ¶·¸C¹!º »Ô»!¹¼½½ 02134576819:<;= 02134KG?316 02134QR;=SUT VW à Á@ÀÅ ¶·¸=¹º »á½¿ ¼¿ º»Æ!À!º Ë #¼½Ñ æ@¼¶áÑ!¼½Ñ æ@¼ ¶ÉÓ >?@A91B4<CDEGFEHE<FEIJ)DJI >?@A91B4<CDEGILLMNMOFPF >?@A91B4<CDEXDPHY<IDFJP Á5¼!º ÄHÌ7Ç¿ ú Ä!Èâ9ãܼÃÈ@½ÏÐÅ ÄÂä #!¼@½Ñæ@¼¶¨ÌÏ=Ê Ñ¼½Ñ æ@¼¶Ò#¶·@¿tÌ åÇ» ÑÁCº Ë@¿å Î å&%5çëÔí òòóçì é5ëóå ÏKÊ Ñ¼½Ñ æ@¼¶Ò#¶·@¿tÌ å"æ,¼ ø!Â!Ã=å Î å'%5çëÍíòò5ðÔðì(ìå Ï,Ê Ñ¼½Ñ æ@¼¶Ò#¶·@¿tÌ åÇ» ÑÁCº Ë@¿å Î & å %5çëþ) ç ( êí ç!ì ) é (å Ï=Ê å %5çëþìë ëìë!í é!ç é5í!å ÏcÊ Ñ¼½Ñ æ@¼¶Ò#¶·@¿tÌ åÙà·@½»Ñ,å Î & Ç Â5¿ÿï ø=½èÓÔѼ½ Ñ æ5¼¶nÒJï ø5ÇÂC¿pÌ7Ï,Ê Ö¿Â!ü¿Àú¿ÂÃÓÍï ø=½cÒ7º¿ ÂÃ!¼¿ ÀÃHÌÏ=Ê äѺ¹ Â Õ Õ ÌJº¿Â!ÃtÒYѼC½'ØÂö5¿pÌÏϳŠÇ!¿ Ã!º ÄÈÍï øÓyÌÇ¿ Ã!º ÄÈ5Ïþº!¿Â!Ã3ÒJÄ!Âö5¿3ÌÏ.Ê Ç!¿ Ã!º ÄÈÔƼ!¹·ÂþÓ ÌJÇ¿ Ã!º ÄÈCÏÿѼ½Ñ æ@¼¶ÒJÈ5¿pÌ#ï ø,Ï=Ê ø *ßå %Íï , ø % . å -!¿Æ¼¹ ·Â/*ñå Çø=½¿ÂÁnÒYÀ ·@¿.Ò#¶@ú!Ä5¿ ¹ ÄHÌ å'ïÂ+ %ÜƼ!¹·!Â5Ï,Ê Õ SAP AG 2004 © SAP AG JA100 7-24 *HQHULF&ROOHFWLRQV 7\SHVDIH &ROOHFWLRQ&ODVVHV The compiler ensures that only suitable objects can be inserted. There is no need for a type conversion when reading the collection elements. -6( SAP AG 2006 Up to and including J2SE 1.4.2, it was the developer’s responsibility to ensure that when collections are used, no cast exceptions occurred when accessing the container objects at runtime. As of J2SE 5.0, container classes can be restricted in such a way that only objects of a specific class can be used. The compiler can check if the correct types are used. The name of the class of permitted objects is written between "<" and ">" and attached to the name of the container. In this way, not only do you define which types are stored in the container object, but the cast that was still necessary with J2SE 1.4.2 is no longer required either. This increases security and makes the program simpler. The option of working with generic types in Java is called ’Generics’. Generics are similar to "Templates" in the programming language C++. © SAP AG JA100 7-25 IRUHDFKORRS (QKDQFHGIRUORRS Sequentially runs through all elements in a data container. Available for arrays and instances of type java.lang.Iterable (for example, collections) -6( SAP AG 2006 Loops are frequently used in Java to process all elements of a collection or an array. An abbreviated form of writing, known as foreach loops, is available as of J2SE 5.0. With this syntactic variant of the for loop, the variable used to reference the individual elements of the data structure is declared first. The colon that comes after it means the same as "from all". The data container that the loop should use to iterate is specified after the colon: for (type variablename : data container) { … } Data container stands for an expression or an instance of the type java.lang.Iterable or an array. In the case of processing a collection, the enhanced for loop works in the same way as the following source code: for (Iterator it = datacontainer.iterator(); it.hasNext(); ) { variablename = it.next(); … } In the following situations, you must still use the conventional for loop: Processing a collection from the end to the start Processing several collections simultaneously Deleting or changing individual elements during processing © SAP AG JA100 7-26 $XWRER[LQJDQG$XWRXQER[LQJ $XWRER[LQJDQG$XWRXQER[LQJ • Automatic conversion between primitive types and wrapper classes. -6( SAP AG 2006 Up to and including J2SE 1.4.2, the developer is responsible for converting between primitive types and the related wrapper classes when required. As of J2SE 5.0, primitive types and wrapper classes can be equally used in most areas. If, for example, a method expects an integer value as an argument, you can transfer an int value instead of an Integer alue. This is converted into an Integer value of equal value without the developer having to do anything. This also works the other way around: The get method shown above can return an Integer value, for example. Since this value is assigned to an int variable, the wrapper object is automatically "unpacked". Similar to the enhanced for loop, this is also a simplified way of writing. That is to say, the compiler takes care of what the developer would otherwise have had to enter in the source code. As a result, the source code is more compact and easier to read. © SAP AG JA100 7-27 &RPSDULQJ 2EMHFWV &RPSDULQJ ZLWK 2SHUDWRU \a_&b c)^| eee f g eee hjilk mnBoBprq qsikRmno tBuwvyxBxx{z \ _&bc^}d ,GHQWLFDO REMHFW" \a_bc)^| \a_&b c^`d FRPVDSWUDLQLQJGHPR&DU#I FRPVDSWUDLQLQJGHPR&DU#I Z [\+]<^`_ SAP AG 2004 The operators “ ==” (equal) and “ !=” (unequal) check whether or not the two objects compared are identical, because the object references (!) are compared here. © SAP AG JA100 7-28 &RPSDULQJ 2EMHFWV &RPSDULQJ ZLWK HTXDOV 0HWKRG \a_bc)^| eee fBg eee h}ik mnBo px~B<nlh}iBk mBno tBu uyvyxBxx{z \a_bc)^}d WKH VDPH FRQWHQWV" \a_bc)^| \a_&b c^`d FRPVDSWUDLQLQJGHPR&DU#I FRPVDSWUDLQLQJGHPR&DU#I Za[O\ ]^`_ SAP AG 2004 If the contents of objects are to be checked for equality, the HTXDOV method is used. The HTXDOV method is defined in the REMHFWclass and is therefore available for every class. If the comparison of two objects with the “ = =” operator returns the value “ true” , you also get the “ true” result when you compare these objects with the HTXDOV method. However, the reverse of this statement is not true. © SAP AG JA100 7-29 7KH HTXDOV 0HWKRG 2 1;)W f n7 <~ Bv CN1<R9?@ :8 4 2 1<;W4 l@ 1? z « « « « « x xx f7B<~Bn ~nB h$ ~+Buv o~7lo< hfBrqq<+Bu+ x xx z ,PSOHPHQWDWLRQ RIWKH HTXDOV PHWKRG LQWKH 2EMHFW FODVV SURYLGHVWKHVDPHIXQFWLRQDOLW\DVWKH³ ´ RSHUDWRU 7RPDNHDFRQWHQWFRPSDULVRQIRUREMHFWVXVLQJWKHHTXDOV PHWKRG\RXPXVWRYHUZULWHWKHHTXDOV PHWKRG SAP AG 2004 © SAP AG JA100 7-30 7KH HTXDOV &RQWUDFW [HTXDOV [ VKRXOGUHWXUQWUXH ,WGRHVQRWPDWWHULI\RXFRPSDUH[ZLWK\RU\ZLWK[ WKHUHVXOWLVWKHVDPH ,I[HTXDOV\DQG\HTXDOV]WKHQ[DQG]DUHDOVRLGHQWLFDO <RXFDQFRPSDUHWZRREMHFWVZLWKRQHDQRWKHUDVRIWHQDV\RX ZLVKWKHVDPHUHVXOWZLOODOZD\VEHUHWXUQHGDVORQJDVWKH REMHFWVGRQRWFKDQJH $OOREMHFWV GLIIHU IURP QXOO SAP AG 2004 In the API documentation for the REMHFW class, you will find the HTXDOV contract under the description of the HTXDOV method. Pay attention to this contract when overwriting the HTXDOV method. © SAP AG JA100 7-31 2YHUZULWLQJ HTXDOV 6XJJHVWLRQIRURYHUZULWLQJHTXDOV LQ\RXURZQFODVVHV ¸+¹º [¶.» $OLDVFKHFN RSWLRQDO ¼2½'¾ ¸+¹º [¶.» ¿ ° 2¡ ¢ £¤¥'¦'§©¨¤«ª ¬¦­¦ ®©¯&° ¨± £¤¥A² ³[)´µ ¶2· [ 7HVWIRU QXOO 'HOHJDWLRQWRVXSHU 7\SHFRPSDWLELOLW\ WHVW ³ [´)µ ¶· [ b c)^ )LHOG FRPSDULVRQ SAP AG 2004 © SAP AG JA100 7-32 2YHUZULWLQJ HTXDOV &DVH'LUHFWVXEFODVVRIREMHFW ÏÐ&ÑÒÓ2ÔÕÔÒÖ×2× ØÙOÚ<Ó2ÔÒOÙÜÛ ÏÝ)ÓÞÖß.Ù à)ßÝÓáâãÞ2ÚÔÒ©äåOæ<Ù)Òlç ÏÝ)ÓÞÖß.ÙèÓá<ß ÞÚÔ)ÒéÒÖ××ç ÏÐÑÒÓ2ÔêÑå2å)ÒÙÖOá Ù2ë2ÐÖÒ×Rì$í&ÑîÙÔßïåßOÚ)ÙÝ<ð,Û $OLDVFKHFN RSWLRQDO ¸ ¹º [O¶.» ³ [´)µ ¶)· [ ì ß&ÚÓ)× ò<òóåß'Ú)ÙÝð ÝÙ<ß'ÐÝOáôß&ÝÐÙ ç Ó2ñ ì`å<ß.ÚÙ)Ýõòò áOÐÒ)Ò ð ÝÙ<ß'ÐÝOáöñ)Ö)Ò)×&Ù ç Ó2ñ ì`å<ß.ÚÙ)ÝR÷â2Ùß&é)Ò2Ö<×2×7ìðøòõâÙßéÒÖ×2×7ì­ð2ð ÝÙ<ß'ÐÝOáöñ)Ö)Ò)×&Ù ç ¼2½&¾ Í [É<Ê.c· Ç2ËA])»$´.[)^à ¸ ¹º [O¶.»jÌÎà ¹ ]]· [Oc)Å À&Á ´¶· Za])ÂO[· ëĻ^µ ÅÆ À&Á ´¶· bR· c.ÇÇ<Ã.µ Å.» È [É<Ê.c· Ç2ËA]2»8´&[)^­Ã ¸+¹º [¶&»jÌà ¹ ]]· [&c)Å Ó2ñ ¡ ¢ £¤¥©¦.§©¨¤«ª ¬¦­¦ ®'¯'° ¨­± £¤¥ ² 7HVWIRU QXOO 7\SHFRPSDWLELOLW\WHVW Ó2ñ )LHOG FRPSDULVRQ ú SAP AG 2004 The diagram shows the HTXDOV ú ì&ø$ÞÚ)Ô)Ò©ä åOæ)ÙÒl÷$Ù)ëOÐÖÒ×Rì ì2ìAØÙOÚÓOÔ)Ò2Ù<ðùåßÚÙ)ÝðB÷ÞÚÔ)Ò©äå2æ)Ù)Òðð ÝÙ<ß'ÐÝOáóñ2Ö)Ò×.Ù ç Ó2ñ ì&ø<ì}Þ2ÚÔÒéÒ2Ö×2×ùò2ò ì2ìAØÙOÚÓOÔ)Ò2Ù<ðùåßÚÙ)ÝðB÷ÞÚÔ)ÒéÒ2Ö<×2×)ðð ÝÙ<ß'ÐÝOáóñ2Ö)Ò×.Ù ç Ý2Ù<ß.Ð)ÝáèßÝÐÙ ç method for the 9HKLFOH class, which is derived directly from REMHFW. y Alias check if ( this == other ) This checks the identity of WKLVand RWKHUfor optimization reasons. y Test for zero if (other == null) The HTXDOV contract demands that all the objects are different to zero. y Type compatibility if ( other.getClass() != getClass() ) This statement checks whether WKLV and RWKHU can be compared at all. Only objects of the same type are comparable. The comparison of an object of a derived class with an object of a corresponding superclass would return “ unequal” . If you wish to allow this type of comparison, you must change the test for type compatibility accordingly. y Comparison of fields if (!vhclModel.equals(((Vehicle)other).vhclModel )) This performs the actual comparison of all attributes of the class. © SAP AG JA100 7-33 2YHUZULWLQJ HTXDOV &DVH,QGLUHFWVXEFODVVRIREMHFW ÏÐÑÒ2ÓÔãÔ)ÒOÖ<×× é<ÖÝ Ù2û<ß&Ù)á2æ<× ØÙÚÓOÔ)ÒOÙÛ ÏÝÓOÞÖß&Ù àß&Ý)Ó)áâõÔÖ2Ýüýlç ÏÐ&ÑÒÓOÔþÑååÒOÙÖOá ÙëOÐÖÒ)×7ì}íÑBîÙ)Ôßïåß.Ú)Ù<ÝðÿÛ Óñ Óñ Óñ ú ú ì ß'Ú<Ó× ò)òôåß.ÚÙ)Ýð ÝOÙ<ß'ÐÝ2áèßOÝÐÙ ç ì ø ×&ÐÏÙ)Ý ÷Ùë2ÐÖÒ× ì`åß.Ú)Ù)Ý<ðð ÝOÙ<ß'ÐÝ2áÕñ)ÖÒ×&Ù ç ìø$Ô)ÖÝ&üý+÷Ùë2ÐÖÒ× ì ìì}é)Ö)Ýðùåß&ÚÙÝðB÷ÔÖÝü)ýðð ÝOÙ<ß'ÐÝ2áÕñ)ÖÒ×&Ù ç $OLDVFKHFN RSWLRQDO ¿ ° ¡ ¢ £¤¥'¦©§.¨­¤©ª ¬¦­¦ ®©¯.° ¨± £¤¥A² 'HOHJDWLRQWRVXSHU )LHOG FRPSDULVRQ ÝÙ<ß'ÐÝOáôß&ÝOÐÙ ç ¸ ¹º [O¶.» È [2ÉÊ&c)· ÇOËj]»8´[^à ¸ ¹º [O¶'» ÌÎà ¹ ]]· [OcÅ ³ [)´µ ¶)· [ ÀÁ ´¶· Za]Â2[· ëĻ^µ ÅÆ ÀÁ ´¶· bR· c&ÇÇõ Å.» È [ÉÊ&c· Ç2ËA]O»´&[)^­Ã ¸ ¹º [O¶&»jÌà ¹ ]]· [c)Å b c^ À ¶&c)^7ÃÄ»8^µ ÅOÆ È [É<Ê&c)· ÇËA]O»8´&[)^à ¸+¹º [¶.»jÌÎà ¹ ]]· [&cÅ SAP AG 2004 The example above shows the HTXDOV thus indirectly from REMHFW) method for the &DU class, which is derived from 9HKLFOH (and y Alias Check if ( this == other ) This checks the identity of WKLVand RWKHUfor optimization reasons. y Delegation to super if ( !super.equals(other) ) The check as to whether the parts inherited from 9HKLFOHare the same is delegated to the superior class. y Comparison of fields if (!carXY.equals(((Car) other).carXY)) This performs the actual comparison of all attributes of the class. © SAP AG JA100 7-34 5HODWLRQVKLS%HWZHHQHTXDOV DQGKDVK&RGH ¸7¹º [O¶.» È [OÉÊ&c)· ÇËA]»´&[)^à ¸7¹º [O¶.»jÌÎà ¹ ]]· [cÅ È ´c.Ç´b ]ÂO[OË ÌÎõ Å&» 0HDQLQJRIWKHKDVK&RGH PHWKRG 8VHGE\V\VWHPWRPDQDJHWKHHQWULHVLQKDVKEDVHG GDWDFRQWDLQHUV +DVK0DS+DVKWDEOH+DVK6HWDQG WKHLUVXEFODVVHV &RUUHFWPDQDJHPHQWRIHQWULHVLQKDVKEDVHGGDWDFRQWDLQHUVEDVHGRQ WKHIROORZLQJLPSOLFDWLRQ RHTXDOV R UHWXUQV WUXH Ö RKDVK&RGH DQGRKDVK&RGH PDWFKRQHDQRWKHU ,QDOOFODVVHVZKHUHWKHHTXDOV PHWKRGLVRYHUZULWWHQWKH KDVK&RGH PHWKRGPXVWDOVREHRYHUZULWWHQVRWKDWWKHDERYH LPSOLFDWLRQLVIXOILOOHG SAP AG 2004 When overwriting the KDVK&RGH algorithms as well): method, proceed as follows (you can, of course, use other y Choose the attributes that represent an object and can be used for implementing HTXDOV y The hashCode should be calculated from the hashCodes of the individual attributes. - If the attribute is a simple data type, you can immediately use its value or the value of the hashCode calculation for the corresponding :UDSSHUclass. If the attribute is a reference variable, you can determine the hashCode with the hashCode method. - Calculate the entire hashCode by adding the individual hashCodes or by using the exclusive or (“ ^” operator) to connect the individual hashCodes bit-by-bit. © SAP AG JA100 7-35 6XPPDU\ <RXVKRXOGQRZEHDEOHWR z 'HVFULEHWKHVWUXFWXUHRIWKH-DYD&ROOHFWLRQV)UDPHZRUN z 8VHWKHPRVWLPSRUWDQWFODVVHVDQGLQWHUIDFHVRIWKH -DYD&ROOHFWLRQV)UDPHZRUN z 6RUWWKHFRQWHQWVRIGDWDFRQWDLQHUV z 2YHUZULWHWKHHTXDOV PHWKRGLQ\RXURZQFODVVHV z 2YHUZULWHWKHKDVK&RGH PHWKRGLQ\RXURZQFODVVHV SAP AG 2004 © SAP AG JA100 7-36 ([HUFLVH 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF /LVWV At the conclusion of these exercises, you will be able to: • Manage objects using the list container MDYDXWLO9HFWRU 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 1-1 1-2 1-3 1-4 1-5 6WDUW8S.LW FRPVDSWUDLQLQJFROOHFWLRQVVRO In your 0\3URMHFW project, create a new package with the name FRPVDSWUDLQLQJFROOHFWLRQVH[F. In this package, define the class %DQNLQJ$FFRXQW in line with the class diagram shown below. The constructor of this class should accept a value for the attribute and transfer it into the attribute. In your FRPVDSWUDLQLQJFROOHFWLRQVH[F packagecreate the class /LVW7HVW. Let the wizard create a PDLQmethod for you. In this PDLQ method, define an object of the class MDYDXWLO9HFWRU and a number of instances of the class %DQNLQJ$FFRXQW, created under step 1-1. You can select the attribute values of the %DQNLQJ$FFRXQW instances as you wish. Use the DGG method to pass the %DQNLQJ$FFRXQW instances to your 9HFWRU object. Then output on the console the value of the attribute EDODQFH for all the %DQNLQJ$FFRXQW instances buffered in the 9HFWRU. To do this, implement a IRU loop over the 9HFWRU content. Remove the entry on the index position 1 from the 9HFWRU. Then output on the console the value of the attribute EDODQFH for all the %DQNLQJ$FFRXQW instances buffered in the 9HFWRU. To do this, again implement a IRU loop over the 9HFWRU content. Test your application. © SAP AG JA100 7-37 © SAP AG JA100 7-38 6ROXWLRQ 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF /LVWV SXEOLF FODVV BankingAccount { SULYDWH IORDW balance; SXEOLF BankingAccount(IORDW balance) { WKLV.balance = balance; } SXEOLF IORDW getBalance() { UHWXUQ balance; } } SXEOLF FODVV ListTest { SXEOLF VWDWLF YRLG main(String[] args) { Vector vector = QHZ Vector(); vector.add(QHZ BankingAccount(1456)); vector.add(QHZ BankingAccount(568)); vector.add(QHZ BankingAccount(0)); vector.add(QHZ BankingAccount(964.7f)); vector.add(QHZ BankingAccount(5563)); IRU (LQW i = 0; i < vector.size(); i++) { BankingAccount account = (BankingAccount) vector.get(i); System.out.println(account.getBalance()); } vector.remove(1); System.out.println("\n---------------------------\n"); IRU (LQW i = 0; i < vector.size(); i++) { © SAP AG JA100 7-39 BankingAccount account = (BankingAccount) vector.get(i); System.out.println(account.getBalance()); } } } © SAP AG JA100 7-40 ([HUFLVH 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF .H\9DOXH3DLUV At the conclusion of these exercises, you will be able to: • Manage key value pairs using the container class MDYDXWLO+DVK0DS 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 2-1 2-2 2-3 2-4 6WDUW8S.LW FRPVDSWUDLQLQJFROOHFWLRQVVRO In your FRPVDSWUDLQLQJFROOHFWLRQVH[F packagecreate the class 0DS7HVW. Let the wizard create a PDLQmethod for you. In this PDLQ method, create an object of the class MDYDXWLO+DVK0DS. Enter a number of key value pairs in the +DVK0DS. The key should be a customer number, the value object should be the customer name. Both the key and the value object should have the data type 6WULQJ. Output on the console all the customer names entered in the +DVK0DS using an LWHUDWRU via the key values. First, use the method NH\6HW to return from the +DVK0DS the sets for all keys. Get an iterator for this key set using the method LWHUDWRU . Use this iterator and the ZKLOH loop to run through the individual key values. In the body of the loop, get from the +DVK0DS the respective value object for the individual key objects and output it on the console. Test your application. © SAP AG JA100 7-41 © SAP AG JA100 7-42 6ROXWLRQ 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF .H\9DOXH3DLUV SXEOLF FODVV MapTest { SXEOLF VWDWLF YRLG main(String[] args) { HashMap map = QHZ HashMap(); map.put("12", "Maier"); map.put("08", "Smith"); map.put("09", "Berger"); map.put("11", "Miller"); Iterator iter = map.keySet().iterator(); ZKLOH (iter.hasNext()) { System.out.println(map.get(iter.next())); } } } © SAP AG JA100 7-43 © SAP AG JA100 7-44 ([HUFLVH 2SWLRQDO 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF 6HWV At the conclusion of these exercises, you will be able to: • Manage objects using the Set container MDYDXWLO7UHH6HW 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJFROOHFWLRQVVRO 3UHOLPLQDU\FRQVLGHUDWLRQV In this exercise you will create a lottery number simulation (“ 6 from 49” ). To create random numbers, you can use the static method UDQGRP from the class 0DWK. It returns a value that is greater than or equal to zero, and is a real number less than 1. Since the values desired are natural numbers between 1 and 49, you must perform the following scaling: LQW num = (LQW)(Math.random() * 49 + 1) The variable QXP now has a whole-number value greater than or equal to 1 and less than or equal to 49. In the data containers of the Java Collections Framework, only objects can be added, meaning no variables with a simple data type. Thus, the value of the variable QXP of the type LQW created above cannot be passed to a container from the Collections Framework. As a workaround, you can pack the values with a simple data type in an object. For this, you have what are known as wrapper classes, in this case the class ,QWHJHU. This means that an object created using QHZ Integer(num) can be put into a data container. 3-1 3-2 In your FRPVDSWUDLQLQJFROOHFWLRQVH[F packagecreate the class 6HW7HVW. Let the wizard create a PDLQmethod for you. In the PDLQmethod, create random numbers between 1 and 49 and put them in an instance of the container class MDYDXWLO7UHH6HW. Implement the random number creation and the passing to the 7UHH6HW instance in the loop body of a ZKLOH loop. The loop should be quit as soon as the 7UHH6HW instance contains six elements. Because a set does not contain duplicates, use this procedure to ensure that six different random numbers are put into the container object. © SAP AG JA100 7-45 3-3 Output on the console the numbers created using an LWHUDWRU via a ZKLOH loop. 3-4 Test your application. © SAP AG JA100 7-46 6ROXWLRQ 2SWLRQDO 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF 6HWV SXEOLF FODVV SetTest { SXEOLF VWDWLF YRLG main(String[] args) { TreeSet set = QHZ TreeSet(); ZKLOH (set.size() < 6) { LQW num = (LQW) (Math.random() * 49 + 1); set.add(QHZ Integer(num)); } Iterator iter = set.iterator(); ZKLOH (iter.hasNext()) { System.out.println( ((Integer) iter.next()).toString()); } } } © SAP AG JA100 7-47 © SAP AG JA100 7-48 ([HUFLVH 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF 6HWV At the conclusion of these exercises, you will be able to: • Manage objects using the Set container MDYDXWLO7UHH6HW • Use the &RPSDUDEOH interface to define a sort on a set of objects 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 4-1 4-2 FRPVDSWUDLQLQJFROOHFWLRQVVRO In this exercise you will extend the class %DQNLQJ$FFRXQW from package FRPVDSWUDLQLQJFROOHFWLRQVH[F. Implement in this class the interface &RPSDUDEOH, which enables the sorting of %DQNLQJ$FFRXQW instances. The sort should be defined in descending order on the basis of the account balance (EDODQFH attribute). To test the sorting, create the class 6RUW7HVW in the FRPVDSWUDLQLQJFROOHFWLRQVH[F package using the PDLQmethod. In the PDLQmethod of this class, create a data container of the type MDYDXWLO7UHH6HW and enter a number of %DQNLQJ$FFRXQWobjects in it. 4-2-1 4-3 6WDUW8S.LW Use an LWHUDWRU to program a loop over the contents of the container. In the loop body, output the content of the attribute EDODQFH for each %DQNLQJ$FFRXQW object in the container. Test your application. Check whether the sorting is correct. © SAP AG JA100 7-49 © SAP AG JA100 7-50 6ROXWLRQ 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF 6HWV SXEOLF FODVV BankingAccount LPSOHPHQWV &RPSDUDEOH { SULYDWH IORDW balance; SXEOLF BankingAccount(IORDW balance) { WKLV.balance = balance; } SXEOLF IORDW getBalance() { UHWXUQ balance; } } SXEOLFLQWFRPSDUH7R 2EMHFWRWKHU$FFRXQW ^ LI WKLVEDODQFH %DQNLQJ$FFRXQW RWKHU$FFRXQW JHW%DODQFH UHWXUQ `HOVHLI WKLVEDODQFH %DQNLQJ$FFRXQW RWKHU$FFRXQW JHW%DODQFH UHWXUQ `HOVH^ UHWXUQ ` ` ^ ! ^ SXEOLF FODVV SortTest { SXEOLF VWDWLF YRLG main(String[] args) { TreeSet set = QHZ TreeSet(); set.add(QHZ BankingAccount(1456)); set.add(QHZ BankingAccount(568)); set.add(QHZ BankingAccount(0)); set.add(QHZ BankingAccount(964.7f)); set.add(QHZ BankingAccount(5563)); © SAP AG JA100 7-51 Iterator iter = set.iterator(); ZKLOH (iter.hasNext()) { BankingAccount account = (BankingAccount) iter.next(); System.out.println(account.getBalance()); } } } © SAP AG JA100 7-52 ([HUFLVH 2SWLRQDO 8QLW &ROOHFWLRQV)UDPHZRUN 7RSLF 7KHHTXDOV DQGKDVK&RGH 0HWKRGV At the conclusion of these exercises, you will be able to: • Overwrite the HTXDOV method inherited from REMHFW in its own class to enable content comparisons between instances of this class • Overwrite the KDVK&RGH method inherited from REMHFW in its own class to be able to store and retrieve instances of this class in hash-based data containers 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 5-1 5-2 6WDUW8S.LW FRPVDSWUDLQLQJHTXDOVVRO In your 0\3URMHFW project, create a new package with the name FRPVDSWUDLQLQJHTXDOVH[F. In this package, define the class &XVWRPHU in line with the class diagram shown below. The constructor of this class should accept values for the two attributes and transfer them into the attributes. In your FRPVDSWUDLQLQJHTXDOVH[F packagecreate the class (TXDOV7HVW. Let the wizard create a PDLQmethod for you. In this PDLQ method, instance two objects of the class &XVWRPHU, created above, with matching attribute values. Use the HTXDOV method to compare these two instances with one another and output the result of the compare on the console. 5-2-1 © SAP AG Although the two &XVWRPHU objects have matching contents, the HTXDOV method still returns IDOVH. What is the reason for this? JA100 7-53 5-3 5-4 5-5 5-6 Overwrite the HTXDOV method in your &XVWRPHU class to be able to make content comparisons between &XVWRPHU instances using the HTXDOV method. Test your application again. The HTXDOV method should now return WUXH for the compare of its two &XVWRPHUinstances. Create an instance of the hash-based container class MDYDXWLO+DVK0DS in the PDLQ method. Use the SXW method to enter a key value pair in this data container, using one of the two &XVWRPHU instances created above as a key object. You can pass any random string as a value object. Read the value object entered in the data container using the JHW method. To do this, call the JHW method twice, passing to it each time as a key object one of the &XVWRPHU instances created under step 5-2. Output the return value of the JHW method on the console. You should have noticed under step 5-5 that you could only access the value object in the container through the &XVWRPHU instance with which you entered the value object in the container. This is in spite of the fact that both &XVWRPHU instances are the same according to the HTXDOV method. What do you need to do so that you can successfully access the content of the data container using both keys (which have identical content)? 5-6-1 © SAP AG Modify the class &XVWRPHU accordingly and test your application again. JA100 7-54 6ROXWLRQ RSWLRQDO 8QLW &ROOHFWLRQ)UDPHZRUN 7RSLF HTXDOV DQGKDVK&RGH PHWKRGV SXEOLF FODVV Customer { SULYDWH LQW id; SULYDWH String name; SXEOLF Customer(LQW id, String name) { WKLV.id = id; WKLV.name = name; } SXEOLF String getName() { UHWXUQ name; } SXEOLF LQW getId() { UHWXUQ id; } //5-3 //public boolean equals(Object other) { // if (this == other) // return true; // if (other == null) // return false; // if (other.getClass() != getClass()) // return false; // if (!(id == ((Customer) other).id)) // return false; // if (!name.equals(((Customer) other).name)) // return false; // return true; //} //5-6 //public int hashCode() { // return id; //} } © SAP AG JA100 7-55 SXEOLF FODVV EqualsTest { SXEOLF VWDWLF YRLG main(String[] args) { Customer customer1 = QHZ Customer(123, "Maier"); Customer customer2 = QHZ Customer(123, "Maier"); System.out.println( "\ncustomer1.equals(customer2): " + customer1.equals(customer2)); //5-4 + 5-5 // HashMap map = new HashMap(); // // map.put(customer1, "dummy value"); // // System.out.println( // "\nHashMap value for customer1: " // + map.get(customer1)); // System.out.println( // "HashMap value for customer2: " // + map.get(customer2)); } } © SAP AG JA100 7-56 ,QWURGXFWLRQWR6$3&RQQHFWLYLW\ &RQWHQWV z 6$3-DYD&RQQHFWRU -&R z 6$3(QWHUSULVH&RQQHFWRU SAP AG 2004 © SAP AG JA100 8-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z ,QVWDOOWKH6$3-DYD&RQQHFWRU z &UHDWHDQ5)&FRQQHFWLRQWRDQ6$3V\VWHP z &DOODUHPRWHFDSDEOHIXQFWLRQPRGXOHLQDQ6$3V\VWHP XVLQJWKH-&R z *HQHUDWHSUR[\FODVVHVWRXVHWKH6$3 (QWHUSULVH&RQQHFWRU z &DOODUHPRWHFDSDEOHIXQFWLRQPRGXOHXVLQJD JHQHUDWHGSUR[\ SAP AG 2004 © SAP AG JA100 8-2 6$3-DYD&RQQHFWRU$UFKLWHFWXUH -$9$ Java application 6$3EDFNHQG V\VWHP SAP Java Connector RFC Function module Java API JNI Layer libRFC RFC RFC Layer 7KH6$3-DYD&RQQHFWRU -&R HQDEOHVWKHFRPPXQLFDWLRQEHWZHHQ DQ6$3V\VWHPDQG-DYD ,WVXSSRUWVERWKLQERXQG -DYDFDOOV$%$3 DQGRXWERXQG $%$3FDOOV -DYD FRPPXQLFDWLRQ -DYDDSSOLFDWLRQVRQO\DFFHVVWKH-DYD$3,RIWKH-&R SAP AG 2004 The SAP Java Connector (JCo) enables you to develop Java applications that access the functionalities of an SAP system. Communication with the SAP system is effected by Remote Function Call (RFC) protocol. A Remote Function Call generally means calling a function module that runs in another system as the calling program. The RFC interface system enables function calls between two SAP systems or between an SAP system and an external system (any random client application). In principle, there is no restriction on which programming language the client application is developed in. With RFC calls, an external application can always access SAP systems. With the introduction of the SAP Java Connector, SAP provides middleware that simplifies calling RFC function modules using Java. Both inbound (Java calls ABAP) and outbound (ABAP calls Java) calls are supported. This means that with JCo, you can create Java server programs whose functionality can be called from an ABAP program. Both Java client and Java server programs only access the Java application programming interface (API) of the JCo. This, in turn, uses an RFC library to communicate with the SAP system on the RFC level. The RFC library is addressed via Java Native Interface (JNI). © SAP AG JA100 8-3 ,QWHJUDWLQJ6$3-DYD&RQQHFWRU -&R LQ6$3:HE $SSOLFDWLRQ6HUYHU %URZVHU 6$3:HE $SSOLFDWLRQ 6HUYHU ! -(( ! -5$ $%$3 -&R JCo -&RLVLQWHJUDWHGLQWKH6$3:HE$SSOLFDWLRQ6HUYHU '%6HUYHU 7KH6$35HVRXUFH$GDSWHUWKDWLVLQWHJUDWHGLQWKH 6$3:HE$SSOLFDWLRQ6HUYHU HQDEOHVVWDQGDUGL]HGFRPPXQLFDWLRQEHWZHHQ-DYD DQG$%$3XVLQJWKH-((VSHFLILFDWLRQ SAP AG 2006 In SAP Web Application Server 6.20 (SAP Web AS 6.20) and higher, SAP JCo is integrated in the SAP system and can be used directly for communication between the Java stack and the ABAP stack. SAP Java Resource Adapter (SAP JRA) is also a component of the SAP Web Application Server (SAP Web AS). It acts as a wrapper for the Java Connector. It was implemented in line with the requirements of JCA 1.0 (Java Connector Architecture). JCA is part of the J2EE specification and enables standardized communication between J2EE servers and non-J2EE servers. © SAP AG JA100 8-4 6WDQG$ORQH ,QVWDOODWLRQ 6$3-&R FDQEHGRZQORDGHGYLD WKH6$36HUYLFH0DUNHWSODFH 3ODWIRUPV VXSSRUWHG :LQGRZV17DQG:LQGRZV /LQX[6RODULV$,;+38; 26DQG7UX 7KHUHDUHDQXPEHURIGLIIHUHQW UHOHDVHVDYDLODEOH SAP AG 2004 You can download the SAP Java Connector at the SAP Service Marketplace: KWWSVHUYLFHVDSFRPFRQQHFWRUV. The SAP Jave Connector is available for the following platforms: Windows NT and Windows 2000, Linux, Solaris, AIX, HP-UX, OS/400, and Tru64. There are also other releases available for download. The selection of releases depends on the area of application of the JCo. You can find further details in the documentation in the SAP Service Marketplace. © SAP AG JA100 8-5 6WDQG$ORQH ,QVWDOODWLRQ ([DPSOH ,QVWDOOLQJDQGXVLQJ-&R LQ:LQGRZV Download the zip file and unpack it into any directory. Copy the file librfc32.dll into the directory C:\WINNT\system32. Add sapjco.jar to the classpath of the Java project. Required import statement: LPSRUW FRPVDSPZMFR SAP AG 2004 If you want to work with JCo 2.0.9 in Windows, for example, you download the relevant zip file from the SAP Service Marketplace and unpack it into any directory on your computer. Among the unpacked files you will find installation instructions and API documentation in html format. To install the JCo, please copy the file librfc32.dll from the unpacked files into the directory C:\WINNT\system32. The JCo classes required in your Java program are in the file sapjco.jar, which was also downloaded with the zip file. Install this file in the classpath of your project. The contents of the bound jar file include the package com.sap.mw.jco. Use the import instruction to bind all the classes it contains into your own coding (“import com.sap.mw.jco.*;”). Now you can start implementing your application. © SAP AG JA100 8-6 &RQQHFWLRQ6HWXS -&2 !#"%$ -&2 &(' ") *,+ -/. . &OLHQW connect():void disconnect():void execute(JCO.Function):void getAttributes():JCO.Attributes ... • An object of the class JCO.Client contains all the information necessary to set up a connection to the SAP back-end system • Options for creating instances: “Direct Connection” via JCO.createClient(...); “Connection Pooling” via, for example, JCO.getClient(...); SAP AG 2004 The SAP Java Connector API uses a large number of LQQHUVWDWLFFODVVHV. These are classes that are defined within another class and are indicated by the keyword VWDWLF. Such classes are not only visible within the class in which they are defined, but can also be instanced from outside. The name of the inner class contains the name of the outer class as a prefix. They are separated from one another by a dot (for example, JCO.Client). The SAP Java Connector supports two types of connection setups to the SAP system: direct connection and connection pooling. In both programming models, a connection to the SAP system is represented by an object of the class JCO.Client. With direct connection, however, the object of the class JCO.Client is created directly in the Java program. When it is created, all the information necessary to set up a connection to the SAP system is passed. Next, the instance method connect() for this object is called, and only now is the connection made. The connection is maintained for as long as the Java program requires, and then it is terminated using the method disconnect( ) from the class JCO.Client. With connection pooling, first a connection pool is created (object of the class JCO.Pool). It contains the logon data for the SAP system and the maximum number of connections to the SAP system. From this connection pool, the Java program can, if required, request an individual connection to work with. In a direct connection, this connection is represented by an object of the class JCO.Client. If the connection is no longer required in the Java program, it can be given back to the pool so that it can be used for other purposes. This programming model is particularly suitable for use in Web applications, but it can also be used in desktop applications. © SAP AG JA100 8-7 &RQQHFWLRQ6HWXS 0 K 132%45%67 89532;:=<?>@4A:#2BC:EDF85G:=HJI v% L MON9P9Q : PR 1?S9T7U2 P 59T9TS87?159T,I V W Z ] 0%b %0 0 0FK 0?L j 0 M 0 V 0 W 0 Z 0%] 0 j Kb 7?6FX P&RQQHFWLRQ Y 2 P 59T9T%S8791?59T\[ NFP9Q :^86?S>7FS PR 1S%T7`_ a9]%bbc d c/k9lmgJn3op%lc d c/s QQ kt@gvu9uc d cwpmo,c d cFnzy{s V b Z bc d cmb%bc ,I 2 P 59T9T%S8791?59TG:8%5?T%TS87`_I :%:9: e%e%f@ghi8 R 1?S%T7 e%eFq<mS%61?r e%e@4><9<3B5%69r e%e R >9T9x9q>9x%S e%e9>m4%4|<mS6?}S6~5<%7UT>32S e%e<3X<97mSm2T9q%29S6 Connection setup via direct connection 89>7?8F~ _p8%S34 7F1%59T\S Y SC:#4v6%1?T7?f7m>%8?k%69>%8S_^JI SAP AG 2004 To set up a connection to the SAP system using direct connection, you must create an object of the class JCO.Client. For this, a constructor of the class JCO.Client is not used, but rather the static method createClient( ) from the class JCO. In the example above, the logon client, user, password, logon data, name of the application server, and system number are passed during the creation of the instance. However, the creation of the JCO.Client instance does not set up a connection to the SAP system. The actual connection setup is only performed when the method connect() is called for the created object. Only now is an attempt made to set up a connection using the values entered when creating the object. Any errors occurring here, such as an incorrect password entry, can be caught using WU\FDWFK. When the connection to the SAP system is no longer needed, it can be terminated by calling the method disconnect() for the JCO.Client object. However, it is not recommended that you set up a connection using direct connection for every call of a function module, only to disconnect it again after the call. This is because constantly logging on to the SAP system generates an overhead which has a negative effect on the performance. It is therefore recommended that you maintain the connection until all the desired calls to the SAP system have been made, and only then call the method disconnect(). © SAP AG JA100 8-8 -DYD5HSUHVHQWDWLYHRID)XQFWLRQ0RGXOH `` P5HSRVLWRU\ 5HSRVLWRU\ Contains the metadata for the function modules to be called mRepository. getFunctionTemplate( “BAPI_SBOOK_CREATEFROMDATA”) IW JC ,J 9 J% )XQFWLRQWHPSODWH Contains the metadata of a function module ft.getFunction() G v( %,G ,J G IXQFWLRQ ,v %v G ,J J % G )XQFWLRQ Represents a function module in the Java program SAP AG 2004 JCo can be used to call RFC-capable function modules, especially BAPIs, from a Java program in the SAP system. In the following example, we use the BAPI BAPI_SBOOK_CREATEFROMDATA to take a closer look at how to do this. The main idea here is that the BAPI or the RFC-capable function module in the Java program is represented by an object of the class JCO.Function. This representative will enable us to supply the input parameters of the function module, to call the function module, and to receive the return value in the Java program after this call. The function object in the Java program is created from a corresponding function template. This function template is also a Java object and contains the metadata for the desired function module, in particular a description of the interface parameters. A description of a parameter includes its name, data type, and data length, plus information as to whether it is an input or return parameter. The function template for a function module can, in turn, be obtained from a repository. This is also an instance, but one that contains the metadata for not only an individual function, but for all the function modules to be called. © SAP AG JA100 8-9 7KH&ODVV-&25HSRVLWRU\ ¡¢9£¥¤¦ §v§ -&2 -&25HSRVLWRU\ P5HSRVLWRU\ P5HSRVLWRU\ QHZ -&25HSRVLWRU\ -$ P&RQQHFWLRQ 7KHILUVWSDUDPHWHURIWKHFRQVWUXFWRU LVDQDPHWKDWFDQEHFKRVHQUDQGRPO\ -&2 5HSRVLWRU\ 7KHVHFRQGSDUDPHWHULVHLWKHUWKH QDPHRIDFRQQHFWLRQSRRORUDQ REMHFWRIWKHFODVV-&2&OLHQW 5HSRVLWRU\ JCO.Repository(String, JCO.Client) JCO.Repository(String, String) getFunctionTemplate(String): IFunctionTemplate %¨¡¢9£ ¤ ¦ §v§ SAP AG 2004 The repository is an object of the class JCO.Repository. Its task is to provide the SAP Java Connector with the metadata of all the function modules that are to be called using RFC. The metadata required can be requested from the SAP system during program runtime. The constructor of the class JCO.Repository expects two input values. The first is a randomly chosen name for the repository, and the second is either the name of a connection pool or a JCO.Client instance. This means that both connection pooling and direct connections are supported for obtaining the metadata dynamically. In Web applications, a connection pool should always be used for the repository. The user through whom the metadata is obtained dynamically from the SAP system must have the appropriate authorizations in the SAP system. To get the required information from the SAP system, the repository must call a series of RFC function modules. The authorization object S_RFC with the fields RFC_TYPE, RFC_NAME and ACTVT is checked. In the required authorizations, the field RFC_TYPE has the value )8*5 and ACTVT has the value (execute). RFC_NAME must contain the name of the function group to which the called function module belongs. The function module called by the repository depends on the release version of the SAP system. It is possible to create a special user for metadata access and to create one or more other users for the actual application. © SAP AG JA100 8-10 &UHDWLQJ WKH -&2)XQFWLRQ 2EMHFW ³³ ¨´3µ·¶¸#¹·º?»3¶F¼?¼ IFunctionTemplate getFunction():JCO.Function -&2)XQFWLRQ7HPSODWH JHW)XQFWLRQ7HPSODWH 6WULQJ IURP -&25HSRVLWRU\ UHWXUQVWKHPHWDGDWD IRUWKHIXQFWLRQPRGXOHVSHFLILHGRU ]HURLIWKHGDWDFRXOGQRWEHFDOOHG 7KHLQWHUIDFHPHWKRGJHW)XQFWLRQ LV XVHGWRFUHDWHWKHDFWXDOIXQFWLRQ XVLQJWKHIXQFWLRQWHPSODWH 0 4q? R 1?8 N9P9Q :^sFqT871?59T©8%6?S>73SvsFqT%87?1?59T_f7?61FT%xªT>32S 7@~6%5?Bv< p?8%S34 7?1?5T«Y 7m6FX Y L nmsqT%87?1?59Tk9Sm24 R >7FSª¬7[ 2vl%S34v5<?17%5%6mX­:^x9S7FsFqT87F1959Tk9Sm294 R >7mS_T%>m2S:E7F5F®?4%4S%6 P >v<mS_9I M 19¬ _¬7¯[%[ T9q R%R V W 6%S7@q69TªTq R9R I 6?S7mq69T ¬7,:°x9S7Fs?qT87F195%T­_ I Z ] 8>7F8~ _(p989Sm4 7?159T\SY j 73~v6%5FB±T9S9B p9v89S34 791?59T_ c?h965@ R Sm26?S7F61?S9}1FTx NFP9Q :^s?qT%879159T©5@DmS87:wc JI 09b 090² K SAP AG 2004 As already mentioned, an RFC function module in the Java program is represented by an object of the class JCO.Function. The instancing of this JCO.Function object is a two-step procedure. First you must create a function template, an object of the class JCO.FunctionTemplate, which implements the interface IFunctionTemplate. The function template contains all the metadata (parameters and exceptions) for an individual function module. To create the function template, call the instance method getFunctionTemplate() from the class JCO.Repository. If this method returns zero, the function module entered could not be found in the SAP system. In the second step, the JCO.Function object is created from the template. For this, use the method getFunction( ) from the interface IFunctionTemplate. The function object does not only contain the metadata, but also the actual parameter values for executing the function module in the SAP system. The relationship between the function template and the actual function is comparable with the relationship between a class and an object in Java. To ease the programming overhead, the coding example encapsulates the creation of the function object in a method called createFunction(), to which the name of the function module to be called is passed. The method returns either the relevant JCO.Function object, or zero if the function module entered could not be found in the SAP system. © SAP AG JA100 8-11 3URFHGXUHIRU&DOOLQJD)XQFWLRQ0RGXOH -&2 0 7F6?X Y NFP%Q :°s?qT879195?T±¬FqT87F195%Ti[ L 73~1< :8%6?S>73SsqT%8791?59T_ c/t@ghnE½ ft Q9Q¾ ½ P l%p3g k%ps?l Q?¿ {mgk/g`c JI M 1?¬ _¬?qT879195?TÁÀ([ T9q R%R Y V e%eÂ<@q?4%4 R Xi4v>6%>@2Sv73S6< W Ä ,Å ,Æ Ç ¶%´mµ :%:9: Z Ç ´3ÈFµ·º´F»m¶ ] 2 P 59T9TS87?1%5?T`:ES9%S89q7mS_(¬%qT87?1%5?Tv I j e%e\S?}> R q>73S\4v>96%>m2S7mS6v< :9:: • • 0FKà 89>7m89~ _p8?SF4 7F195%T\SY ?0 L S%C:#4v61?T79f7m>%8%%k%6>%8?S_EI 0 M K -&2 )XQFWLRQ getExportParameterList(): JCO.ParameterList getImportParameterList(): JCO.ParameterList getTableParameterList(): JCO.ParameterList getExceptionList(): JCO.AbapException[ ] ... v ¡v¢%£ ¤¦ §§ )XQFWLRQ SAP AG 2004 The coding shown here shows the necessary steps for calling the function module BAPI_SBOOK_CREATEDFROMDATA in the SAP system. First, the relevant Java representative, an object of the class JCO.Function, is created using the utility method createFunction(). You can access the parameters of a JCO.Function object using the methods getImportParameterList( ), getExportParameterList( ), and getTableParameterList( ). These methods return an object of the class JCO.ParameterList that contains all import, export, and table parameters for the relevant function module. If no parameters of the specified category exist for the function module in question, the relevant method returns a zero. The entry interface of the function object must be supplied using the methods named.. Use the method execute( ), which is called for the JCO.Client object and to which the JCO.Function object is passed, to call the function module in the SAP system. After the call, the return values must be accepted in the Java program. For this, use the methods getExportParameterList( ) and getTableParameterList( ). © SAP AG JA100 8-12 6XSSO\LQJWKH,PSRUW3DUDPHWHUV -&R N9P?Q :h9>%6%>@2Sv73S6?u1<71@29½4v>96>@2[ ¬?qT%8791?59TG:^x%S7nw245967Fh9>69>32S73S69u1<%7G_I N9P?Q :f7F6?q87mq69S\5591?Txi[ 1@2?½4v>69>32:^x%S7?f7969q87@q6%S­_ c/t Q9Q¾ nÉoÊ9{mgkFg9½Ënzo,c I -&R ;Ì v v 3DUDPHWHU/LVW Import parameter interface BOOKINGDATA_IN getField(String): JCO.Field getField(int): JCO.Field getStructure(name): JCO.Structure getStructure(int): JCO.Structure getTable(name): JCO.Table getTable(int): JCO.Table ... CARRID CONNID FLDATE CUSTOMID SMOKER LUGGWEIGHT WUNIT CLASS COUNTER AGENCYNUM %$3,B6%22.B &5($7()520'$7$ SAP AG 2004 The function module BAPI_SBOOK_CREATEFROMDATA only contains one import parameter, namely a structure called BOOKINGDATA_IN. This is used to pass the required information to the function module so that it can make the corresponding flight booking in the system. To be able to supply the input parameter BOOKINGDATA_IN from the Java program, the method getImportParameterList( ) is called for the function object, and it returns an object of the class JCO.ParameterList. This object can be used to request a Java representative for the structure BOOKINDATA_IN. Within a parameter list, you can access the individual parameters via their type (field, structure, or table) or their name. The methode getStructure( ) allows you, for example, to access a random structure-type parameter within a parameter list. Using getStructure(“BOOKINGDATA_IN”) you thus gain access to a Java instance thath represents the import parameter of the function module. It is of the type class JCO.Structure. © SAP AG JA100 8-13 6XSSO\LQJWKH,PSRUW3DUDPHWHUV v ¡¢%£ ¤¦§ § ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ Ý%Þvß­Ý à Ý%á9âGãvã`ä9åAÝ æCç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ Ýèéè è,Ý à ÝáêvëëCäåÝ æ`ç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ ÝìJèèËívèJîï ðÝ à Ý?ñJÞåâ,òóCÝ æCç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ Ýèèè èèJèvèËéËÝ à Ý?áô,õòêvö`äåÝ æAç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ ÝF÷Ý à Ýõ%öËêJøvóJã­Ý æAç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ Ýì ðùÓ3ú èJèvè`Ý à ÝFÞô,ûûüJóCäû ß ò`Ý æCç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ Ý?ø ûCÝ à Ý@ü ô ëGäòGÝ æAç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ Ý%ñ`Ý à Ý?áJÞ9âAõvõ`Ý æ­ç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ ÝJÝ à Ý9áêôëCòóJã­Ý æAç ÍÎÎJÏ ÐÑÒ¥Ó/ÔÕ Ö?×GØ ÙÚÕÜÛ Ýìýï,Ý à ÝÉâCûóëávþë ôöùÝ æ`ç Filling the interface and executing the function module ERRNLQJ CARRID CONNID FLDATE 20060713 LH 0400 ÿ áÎ ÑÑ Õ,ÖÐvÎ Ñ ÓzÕJÕÚËÖvÕ ÛvÚ ÑÖ ÐÎ Ñ,æ­ç CUSTOMID SMOKER X 00000004 v LUGGWEIGHT WUNIT CLASS COUNTER AGENCYNUM 23.5000 KG F 291 BOOKINGDATA_IN IXQFWLRQ %$3,B6%22.B &5($7()520'$7$ P&RQQHFWLRQ , JC% J 9 SAP AG 2004 A structure is a complex data type, which means that our import parameter BOOKINGDATA_IN is made up of individual components. To pass values for the individual components, the method setValue() can be called for the Java representative of this structure. There are many overloaded versions of this. The variant used in the example expects two strings on the interface: The first string is the value for a component, and the second is the name of the component. So supply a component with its type-related initial value, the value “” is passed. When passing a date, you must ensure that it is passed in the ABAP-internal format: YYYYMMDD. After the interface is supplied, the function module is called using the method execute(). Thus, the values for the input parameters are passed to the SAP system and the function module is processed. © SAP AG JA100 8-14 (YDOXDWLQJWKH([SRUW3DUDPHWHUV v ¡ ¢%£ ¤¦ §§ N?P9Q :^h9>69>32Sv7mS%69uv1<97S?3½4>%6>32±[ ¬?q%T87?1959TG:^x%S7mp?4567Fh9>69>32S 73S6%u1<97`_I N?P9Q :^f7?6Fq87mq6?S69S7mq6?Tf7m6?qv87@q6%Si[ S9@½4v>%6%>32:^x%S7?f76Fq87@q6%S­_ cwlp%kF®l3oc JI N?P9Q :^f7?6Fq87mq6?S\v595%1FT%x1FT¬5[ S9@½4v>%6%>32:^x%S7?f76Fq87@q6%S­_ cwt Q9Q¾ nÉoÊ?{FgkFg,c I UHWXUQ6WUXFWXUH TYPE ... ... ... MESSAGE ... ERRNLQJLQIR ... ... BOOKID ... ; v v ... ... Export parameter interface ... ... RETURN IXQFWLRQ TYPE ... ... ... BOOKINGDATA %$3,B6%22.B &5($7()520'$7$ MESSAGE ... ... ... BOOKID ... ... ... ... ... J,` ,Ë J v% GA% SAP AG 2004 The function module BAPI_SBOOK_CREATEFROMDATA has two export parameters. One is the RETURN structure typical for BAPIs, by means of which the BAPI informs the caller of any errors that arise, and the other is the structure BOOKINGDATA, from which the user can get information on the flight booking created, especially the booking number (component BOOKID) assigned in the SAP system. To access the return value after the function module is called, call the method getExportParameterList( ), which returns an object of the class JCO.ParameterList. From this export parameter list, you can use getStructure( ) to gain access to Java representatives of the two export structures. These Java representatives are instances of the class JCO.Structure. © SAP AG JA100 8-15 (YDOXDWLQJWKH([SRUW3DUDPHWHUV v ¡v¢%£ ¤¦ §§ Ð Û GÛ ÕJÖÚ Ñ õÖÚ ÖvÚ Õ Ó=ÒJÕËÖJõÖÐÑJÒ Û Ý?òþóCÝ æùÓ=Õ ÚËØ Ù,Ô;Û ÝJÝ æ ÕJÖÚ Ñ õÖÚ ÖvÚ Õ Ó=ÒJÕËÖJõÖÐÑJÒ Û Ý?òþóCÝ æùÓ=Õ ÚËØ Ù,Ô;Û Ýõ,Ý ææ æ Ö Î ÑËÕ óÕ` ÖÐvÎvÑ Û ÕËÖÚÑËõÖÚ JÖÚÕ;Ó=ÒJÕËÖJõÖÐÑvÒÜÛ Ý@öËó,õJõFâ`ûóÝ ææç õGÔ ÖÕ ÿ Ó/ÎÚ,Ö;ÓÐÑËÖÙÑÜÛ 9ÑvÚ ÿ ÍÕ -&R Î ÕÑ,Ö! Ý " ÍËÎJÎÏËÐÑJÒ ÐÑ ÎÓ=ÒJÕËÖJõÖÐÑJÒ Û Ý$#ËêêøCä?åÝ æJæ­ç -&R 6WUXFWXUH getField(String): JCO.Field getField(int): JCO.Field getString(String): String getString(int): String setValue(String, String): void setValue(Object, int): void ... number of entry: 00012489 SAP AG 2004 First the content of the RETURN structure is evaluated. We are most interested in the values of the components TYPE and MESSAGE. The TYPE component tells us whether an error occurred during the processing of the function module in the SAP system. If no message type, or the message type S (“success”) is returned, this means that the processing of the BAPI in the SAP system was successful. If no error occurred in the SAP system, we obtain from the second export structure the booking number of the booking created in the SAP system and output it on the console. If the TYPE component indicates an error situation, we obtain the message text for the error from the component MESSAGE and use this text to trigger an exception in the Java program. The method getString( ) is used to evaluate the components. It returns the content of a component as a Java string. © SAP AG JA100 8-16 &ORVLQJD7UDQVDFWLRQ J v v %1&2(*) +J 3, & %'& (*) +Ë -, &Ë %.& ( %0/ , +I F G2H 4J57=8 8;:=<K>@? 798LA <=798M8;:=<K>ND E 4657988;:=<=>@?*7=8 A :3B:=<C9>*:=D A A A E BAPI_SBOOK_ CREATEFROMDATA BAPI_TRANSACTION_ COMMIT '% SAP AG 2004 Most BAPIs that make database changes do not perform the COMMIT WORK themselves. These BAPIs require an additional external commit to store the changes on the SAP database. This programming model enables you to call a number of BAPIs that carry out database updates, represented by a Logical Unit of Work (LUW). The LUW is only terminated when the function module BAPI_TRANSACTION_COMMIT is called, which performs the database commit. The update BAPIs and the commit BAPI must be called within the same SAP session. This means that the connection to the SAP system must be maintained for the entire LUW. It may not be terminated in between using the method disconnect( ) for direct connection or releaseClient( ) for connection pooling. The function module BAPI_SBOOK_CREATEFROMDATA creates a flight booking in the SAP system, meaning that it performs a database change. This function module does not perform the COMMIT WORK itself either, which means that an additional external COMMIT is also required here. Calling the function module BAPI_TRANSACTION_COMMIT terminates the LUW and performs the database change. © SAP AG JA100 8-17 &ORVLQJD7UDQVDFWLRQ v % ¡ v¢9£ ¤¦ §§ K 0 L 7F6mX M V W Y FN P9Q :°s?qT87?1%5?Tª¬9qT8/½8%5m29217i[ 73~1< :8%6?S>7FSsqT%8791?59T­_ cmt3g hn=½k%l3g%ofmg P kvn Q o?½ P?Q¿9¿ n3kc I 1?¬ _¬?qT8w½ 8%5@2%2v17 À [ T%q R%R Y 2 P 59T9TS87?1?5%T`:ES9%S89q7mS­_(¬qT8w½895m2%2v17 I ]² 8 >7m8?~ _p8?SF4 7F195?T©SY j 9e e3~>?T%r R S73~%S\S%8Sm47?1%5?T 0%b² Z '% %$3,V IURPUHOHDVHSHUIRUP&200,7:25.WKHPVHOYHV )URP5HOHDVHWKLVVKRXOG QRORQJHUEHWKHFDVH D 7UDQVDFWLRQ KDQGOLQJ XVLQJ 6HUYLFH%$3,V • 7UDQVDFWLRQ&RPPLW IXQFWLRQ PRGXOH %$3,B75$16$&7,21B&200,7 SAP AG 2004 • 7UDQVDFWLRQ5ROOEDFN IXQFWLRQ PRGXOH %$3,B75$16$&7,21B52//%$&. The function module BAPI_TRANSACTION_COMMIT has no obligatory input parameters. This means that to call it, you simply use your utility method createFunction( ), described above, to create the related JCO.Function object and initiate the processing of the function module in the SAP system using the method execute( ). When using update BAPIs, you must note that BAPIs from release 3.1 perform the COMMIT WORK themselves, while BAPIs as of release 4.0 should not contain COMMIT any more. However, there are also exceptions among the BAPIs from release 4.0 which trigger the COMMIT WORK command themselves and thus complete the transaction. BAPIs with an integrated COMMIT WORK cannot be combined with other BAPIs within an LUW. When working with update BAPIs, you should always be sure which transaction behavior is implemented in the respective BAPI. SAP Note 131838 documents the BAPIs that were created using the transaction model for 3.1 with COMMIT WORK, as well as the few exceptions from later releases. Note that the completeness of this note cannot be guaranteed; always read the documentation on the BAPI. Transaction handling includes, along with the BAPI TransactionCommit (which incorporates the function module BAPI_TRANSACTION_COMMIT and triggers the COMMIT WORK in the SAP system), the BAPI TransactionRollback. This BAPI incorporates the function module BAPI_TRANSACTION_ROLLBACK, which performs a rollback in the SAP system. © SAP AG JA100 8-18 6$3(QWHUSULVH&RQQHFWRU ³1DWLYH´ -&R 6$3(QWHUSULVH&RQQHFWRU k U pUfP ` W SXV k U pUfP ` W SXV Proxy classes Runtime Framework k P.\ _ U `N` %'& /*/ JCo O')% PRQTS;U;V-W*XY[ZQT\]^ _` UMaMaS a b a W*XYcV-dSfe2g1h i XMV SQjZ QjW aS P'\ XXS _ V \ Q RFC Function module JCo l.m P RFC Function module e2g0hna^aMVSo e2g0hna^a;V So SAP AG 2004 The SAP Enterprise Connector is a development tool that generates helper classes for calling RFC function modules in Java applications. These helper classes are also known as -DYDSUR[LHV. The example above shows the difference between RFC calls with and without a Java proxy. In the Java client, the generated Java proxy hides the interaction with the middleware level, meaning the native JCo calls. This architecture guarantees type-secure data access and increases the stability of the client application. The Java proxy runtime framework also keeps the handling of single-byte and unicode systems transparent for the application developer. This means that the application developer does not have to convert function parameters between single-byte characters and unicode characters. The SAP Enterprise Connector is integrated into the SAP NetWeaver Developer Studio as a plug-in. © SAP AG JA100 8-19 *HQHUDWLQJ&ODVVHV -DYD3UR[\ vwx h \ QyV z^ ZS l _ x m b X _ V-W \ Xon\ b ` S x X Z b V l _ xm b X _ V-W \ Xon\ b ` S x ¢ b V3Z b V 9=*@L{@ 9$NN {N KNN;{N K*N {@ Changing Parameter {N|~}u =}T ;1LL = |@}L K}$y L.MM ;*MLy |~}uL K}T M M $L$ Exceptions W _ aMV-Q b _ V b QyS;z^ZS W _ aMV3Q b _ V b QTSMz^ ZS x W aMV KT }K=y{=}$y{K K9*$@ ; }=y{=}${@=9MK 9=y; }$KT{T=}$y {@=9MK9~ @¡LM }=y{ K}$yL{~K L=$ }K=y{=}$ {@=9MK K*@L{@ 9$@N {N qrSXSQU V-W*XYtscW V-drVudSJe2g.h i XVSQjZ QjW aMSnP.\XXS _ V \ Q $%$3 IMPORT parameter 5)&B)XQFWLRQPRGXOH EXPORT parameter CHANGING parameter TABLE parameter Exceptions Structure types from the ABAP Dictionary SAP AG 2004 For every structure-type dictionary type that is referenced by an RFC function module to be called, the SAP Enterprise Connector generates a separate Java class. The proxy generation follows the design pattern of the JavaBean. This means that for the individual components of a structured dictionary type, attributes of the same name are declared in the generated Java classes. For every attribute of a generated class, type-secure getter/setter methods such as getCarrid( ) and setCarrid( ) are generated. Along with the type classes just mentioned, the SAP Enterprise Connector also generates an input class that contains all the importing, changing, and table parameters of the function module to be called. In a similar way, the tool also generates an output class that combines all the export, changing, and table parameters. The class names are made up of the name of the function module followed by the character string “_Input” or “_Output”. The individual parameters are defined as attributes of the classes, which the calling program can read or write to using getter and setter methods. The SAP Enterprise Connector provides table parameters as a list that can be used by an RFC function module. For this purpose it generates, for every table, parameter a Java class that represents the data type of this parameter as a Java list. The corresponding objects are contained in the output object after the RFC call. Since the row type of a table is always of a dictionary structure type, the SAP Enterprise Connector also creates a Java class for this row type. © SAP AG JA100 8-20 *HQHUDWLQJ&ODVVHV -DYD3UR[\ Changing Parameter Exceptions l.m P xm b X _ V3W \ Xon\ b ` S xm U b ` V xi ] _ SZV-W \ X l'm P xm b X _ V3W \ Xon\ b ` S xm U b ` V $ |@} =}9T L $£ L @@ |@}9}T M L K£ M 9K |@}LK}Ky ;¤MM $£ L ~ |@}; K}$y L.MM =£LL N u¥;M 9K*N;{N =K*@L{@ qrSXSQU V-W*XYtscW V-drVudSJe2g.h i XVSQjZ QjW aMSnP.\XXS _ V \ Q $%$3 IMPORT parameter 5)&B)XQFWLRQPRGXOH EXPORT parameter CHANGING parameter TABLE parameter Exceptions Structure types from the ABAP Dictionary SAP AG 2004 When generating, you also create a class whose name is made up of the name of the function module followed by the character string “ _Fault” . This IDXOW type represents the exceptions of the function module. With the method getText( ) from this class, the calling program can obtain the technical name of the exception that occurred during exception handling. Along with the IDXOW type, another Java exception class is generated whose name is made up of the name of the function module followed by the character string “ _Fault_Exception” . This exception class, which encapsulates the IDXOW type, can be caught and handled by a Java program in a FDWFK block. A JHWWHU method of this exception class returns the IDXOW type. The generated Java proxy class, knows as theSRUW type, represents the function module to be called. The class name is made up of the entry you make for generating and the character string “ _PortType” . This class contains a method with exactly the same name as the function module to be called. This method is used to call the function module in the remote system. When it makes the call, the method demands an instance of the input class and returns an instance of the output class. When the function module is called, exceptions may be triggered. The SAP Enterprise Connector combines all the generated type classes and the Java proxy together in one package whose name must be entered in the generating process. © SAP AG JA100 8-21 *HQHUDWLQJ&ODVVHV([DPSOH -DYD3UR[\ e ` W YdVuhQ\]M^ x h\ QyVz^ ZS Changing Parameter e ` W Y dMV x qRS;V ` W aMV x X Z b V =|y M² ³Ky =@ 9 =@µ£ {T{ L ´ T{T KL -¥; ´ |T ² M³Ly K ;*LM~ 9 =@µ ;L M ´ y{ =9¥M ´ |T ²= ³ Ky K $L= ¶¶¶ Exceptions e¤Z ` W z^ZS e ` W Y dVz^ ZS 9K@µ2 ~|{~r ´ y{ 9K@µ2 ~ ´ y{ K e ` W Y dV x qRS;V ` W aMV x ¢ b VuZ b V L$~µ MM$}T * ´ 9|y LLK L$ L£K 9y M²K* N ´ |y M²9N L=¬L = e ` W Y dVz^ ZS x W aMV $ ´ | ;²9~LLK=*$@ ´ |T ²$@ L$ =K ´ |y M²~LM$~ $~¡ ´ |T ²=@;K= ´ |y M²9N LK 9Ky £$~L K£$@ 9Ky§{T }K=*yK« ;} £; qrSXSQU V-W*XYtscW V-drVudSJe2g.h i XVSQjZ QjW aMSnP.\XXS _ V \ Q $%$3 6)/,*+7B*(7/,67 ¦0§; =£L{~£91KN { L¨ © § $£ {@£LK~L{ 9 ª2«¬ ¨ $£L{£=N { carrid connid connection TYPE SPFLI flights LIKE SFLIGHT ¨­ }$;T carrid_not_found connid_not_found db_failure e V3Q b _ V b QySJVT^ZS;a Q\ o®V-dS¯g0°2g0h W _ V3W \XUQ^± SPFLI SFLIGHT SAP AG 2004 We now want to look at an example that clarifies the generation of a proxy using the function module SFLIGHT_GETLIST. This contains, for example, an exporting parameter CONNECTION, which references the transparent table SPFLI. This means that CONNECTION is structured in the same way as a row of the database table SPFLI, thus as a structure type. The SAP Enterprise Connector represents the data type SPFLI in the Java class SpfliType. Using the getCityfrom( ) method created, the calling program can, for example, read the value of the component CITYFROM. The Sflight_Getlist_Output class generated contains all exporting and table parameters of the function module SFLIGHT_GETLIST. The method getConnection( ) of this class returns the value of the exporting parameter CONNECTION, namely an object of the class SpfliType. The function module SFLIGHT_GETLIST also has a table parameter called FLIGHTS, which contains rows from the dictionary type SFLIGHT. The SflightType_List class generated represents the type of the table FLIGHTS, and the class SflightType represents its row type SFLIGHT from the ABAP Dictionary. The method get_as_listFlights( ) from the class Sflight_Getlist_Output returns the entire table as a list, namely as an object of the class SflightType_List. The indexed getter method getSflightType( ), which can be called for this list object, returns a table row of the type SflightType. Finally, you can use the getter methods for this “ row object” to read the values of the individual row elements. © SAP AG JA100 8-22 *HQHUDWLQJ &ODVVHV([DPSOH -DYD3UR[\ Changing Parameter Exceptions e ` W Y dV x q¸SMV ` W aMV xm U b ` V e ` W Y dV x qrS V ` W a;V xm U b ` V xi ] _ SZV3W \ X $@ ­ ~ ´ y{T 9 $ ´ |y M²9 ;³Ky 9 $£ ~~ ´ |y ² M³T = K£ L $T¹£91L ´ |T ;²$ ³$ = K£ ¶ ¹£;¤= L$ 9K ´ |T ² ;³Ly K =£LL T ´ |y ²$ ;³ $T $£L -¥M; qrSXSQU V-W*XYtscW V-drVudSJe2g.h i XVSQjZ QjW aMSnP.\XXS _ V \ Q $%$3 6)/,*+7B*(7/,67 ¦0§; =£L{~£91KN { L¨ © § $£ {@£LK~L{ 9 ª2«¬ ¨ $£L{£=N { carrid connid connection TYPE SPFLI flights LIKE SFLIGHT ¨­ }$;T carrid_not_found connid_not_found db_failure e V3Q b _ V b QTSJVy^ ZS a Q\o·VudSJgR° gRh W _ V3W \ XUQ^± SPFLI SFLIGHT SAP AG 2004 In SFLIGHT_GETLIST, three ABAP exceptions are defined: CARRID_NOT_FOUND, CONNID_NOT_FOUND, and DB_FAILURE. The generated class Sflight_Getlist_Fault_Exception represents a Java exception that can be caught and handled in the program using WU\FDWFK. The getter method getSflight_Getlist_Fault( ) returns an instance of the fault type Sflight_Getlist_Fault, from which the method getText( ) can be used to request the name of the exception that occurred: CARRID_NOT_FOUND, CONNID_NOT_FOUND, or DB_FAILURE. In our example, the proxy class SflightProxy_PortType contains the method sflight_Getlist() for the function module SFLIGHT_GETLIST. This method requires an instance of the class Sflight_Getlist_Input as an input parameter and returns an instance of the class Sflight_Getlist_Output. If applicable, the method triggers exceptions of the class Sflight_Getlist_Fault_Exception. © SAP AG JA100 8-23 &DOOLQJD)XQFWLRQ0RGXOH8VLQJ 6$3(QWHUSULVH &RQQHFWRU 8VLQJWKHJHQHUDWHGFODVVHVIRU WKHIXQFWLRQPRGXOHFDOO õ ö ÷ Create a connection to an SAP system. Supply data to entry parameters. Create an instance of the proxy class generated and supply it with a connection object (object of the class JCO.Client). º »L»½¼K¾K¿L¿ÀKÁ¿ÃÄLÃ$ÅÆÇKÆLļ ÈÊÉËLÀLÌÍ9ÎÇ-ÏÐLÆÇ9ÀÌ;¼LÇ-ÏÑ$Ò$¿¾ÇÓÌ9ÒK¿M¾ÇÕÔ ÒLÆÖ É9Ë;ÀLÌ=Í;ÎÇ-ÏÐ ÆÇ=ÀLÌM¼;Ç-ÏÑ$Ò$¿M¾Ç2×ØÙ ÚÛÌ9Ò$¿M¾ÇÜ3¼KÆÇKÝÃLÄÄ Ì9Þ.× ßàLáß Ø Ù â Ì9Ò$¿M¾ÇÜ3¼KÆÇKÝãÒÒ;Ì9Þ.× ß=ä â ä;äß ØÙ å æ »L»ç Ä9Æ ÃMÇKƽ¿Äã9èÁéÃÒÞê¼K¾K¿L¿À$ÁëÌ ÇÓÖMÌ;Ç$ÎíìÝ ã2ÜjÝ;ÀLÌ=Æ ÒÇîÌÒ¼LÇ=ÃÒLçÆ ï ÉËLÀLÌÍ9ÎÇ9ðÄLã èÁ$ÏðãLÄMÇ=ñKÁ¿Æ¿ÄLã9èÁòÔ ÒLÆÖ É9Ë;ÀLÌ=Í;ÎÇ9ð9Ä ã9è9ÁKÏ ð ãLÄMÇ=ñKÁ9¿Æ1×ØÙ óô¿Äã9èLÁ¤Ü~ÅƼL¼LÃÍÆ;É¿Æ ç Ì9Ë;ÌLÆ;Ä2Ü3¼KÆMÇìçã;Ý;ÀLÌ9ÆLÒÇ2×NÅÝLã;ÒLÒLÆLçÇ9Ì9ãÒØÙ SAP AG 2004 To work with the classes generated by the SAP Enterprise Connector, you must include the following jar files in the CLASSPATH: aii_proxy_rt.jar, aii_util_misc.jar, SAPmdi.jar, and sapjco.jar The connection to the SAP system is structured exactly as was described in the discussion of the JCo. With a connection setup using direct connection, you first have to create an object of the class JCO.Client with the connection data. Next, the method connect() for this object is used to create the connection to the SAP system. Connection pooling is also supported. This means that a connection can be added to a connection pool for reuse and can be taken from there when required. The entry parameters of an RFC function module are supplied with the relevant values through the creation of an instance of the generated input class. Using setter methods, you can pass values to the parameters. To call a function module in the SAP system, you have to create an instance of the generated proxy class. This proxy instance must in turn be supplied with a connection object. © SAP AG JA100 8-24 &DOOLQJD)XQFWLRQ0RGXOH8VLQJ 6$3(QWHUSULVH &RQQHFWRU 8VLQJWKHJHQHUDWHGFODVVHVIRUWKHIXQFWLRQPRGXOHFDOO Call the RFC function module Handle possible exceptions in using the method of the same the call. name from the proxy object. È ºøÉË;ÀÌ9ÍÎÇ-ÏÐÆÇ9ÀLÌ;¼LÇ-Ïù ¾Çu¿¾Çîã9¾Çu¿M¾ÇîÔ Ò9¾ÀLÀ Ù Ú Ç=Ä9Á ú ã9¾Ç¿M¾ÇÓÔî¿ÄLã=èLÁ1Üj¼LË ÀLÌ9ÍÎÇ3ÏÐ ÆÇ9ÀLÌ;¼Ç×TÌ=ÒK¿;¾ ÇLØ Ù â å û çÃMÇ=ç9Î ×yÉ;Ë À Ì=ÍÎÇ3ÏÐLÆMÇ ÀLÌ;¼LÇ-ÏýÃ9¾ÀÇ-Ïþè çLÆK¿Ç9Ì9ãMÒòÆØëú ü æ ÉË ÀLÌ9Í9ÎÇ-ÏÐÆÇ9ÀÌM¼LÇ3ÏýLÃ9¾MÀ;ÇËLþÀ;ÇÿÔ ×yÉË ÀLÌ9ÍÎÇuÏÐÆÇÀ̼ Ç-ÏýLþ;À;ÇLØÓƤÜÍÆÇ=ÉLË ÀÌ;Í9ÎÇuÏÐLÆMÇ9À Ì ¼Ç3ÏýþMÀ Ç×jØÙ ï ó ÉKÁ¼LÇKÆ$ÅRÜ ã¾ÇÜ~¿Ä;Ì9ÒMÇ À9Ò.× ßýLÃ=¾MÀMÇÕÅƼ¼=ÃLÍÆéÇLÆ9è Ç ß éËLÃ=¾MÀMÇÜÍÆÇ=ñ;ÆèÇ× ØØÙ ÉKÁ¼LÇKÆ$ÅRÜÆLè;Ì;Ç׺;ØÙ º ä û çÃMÇ=ç9Î ×yÉÁ¼ Ç$ÆKÅýþMÀ Çþè;çÆK¿Ç=ÌãLÒíÆØëú º º »L»=áLÃÒÞÀ9Æ Ç$Î ÆòÆè ç;ÆK¿Ç=ÌLãÒ º9È û çÃMÇ=ç9Î × ¿L¿ÀÌçLÃ;ÇÌã9ÒýLÃ9¾MÀ;ÇKþ9è;çLÆ9¿Ç9Ìã9ÒÂÆØëú ºÚ »L»=áLÃÒÞÀ9Æ Ç$Î ÆòÆè ç;ÆK¿Ç=ÌLãÒ º â û SAP AG 2004 The function module is called via the instance method of the same name from the proxy class. This method expects as an input parameter an instance of the generated input class and, if the call is successful, it returns an instance of the generated output class. The SAP Java Connector, the Java proxy framework, and the RFC calls themselves trigger exceptions during runtime to signal errors in the running of the program. To catch these errors and handle them appropriately, insert WU\FDWFK blocks in the program code. During runtime, three different types of exceptions can occur: SystemFaultException, ApplicationFaultException, and a third exception that is specifically for the called function module. In our example, it is called Sflight_Getlist_Fault_Exception. It includes all the exceptions that are defined in the function module and thus signals errors from application logic in the SAP system. The function module SFLIGHT_GETLIST defines three exceptions. Using the method getText( ) of the generated class Sflight_Getlist_Fault, you can query the technical name of the exception that actually occurred. SystemFaultException and ApplicationFaultException indicate errors in the proxy framework. SystemFaultException indicates errors on the technical level, and ApplicationFaultException signals errors on the application level. © SAP AG JA100 8-25 &DOOLQJD)XQFWLRQ0RGXOH8VLQJ 6$3(QWHUSULVH &RQQHFWRU 8VLQJWKHJHQHUDWHGFODVVHVIRUWKHIXQFWLRQPRGXOHFDOO Evaluate return parameters of the function module after the call. End the connection to the SAP system. º »L»Æ Ã;À=¾ ÃMÇÆÿ¿ÃLÄÃ$ÅÆMÇKÆÄM¼ ÈÊÉ¿ËLÀLÌ9ñ9Á9¿MÆ çLã9Ò ÒLÆLçMÇ9ÌãÒíÔÂã¾Ç¿M¾Ç2Ü ÍLÆMÇKÝ ãÒLÒLÆLçÇ9ÌLã9Ò.×ØÙ ÚÛÉKÁ¼ÇKÆ$ÅÜ ã=¾ÇÜ~¿Ä;Ì9ÒMÇ9ÀÒ1× ßKÝ;Ì ÇÁËÄLã$Å ÿß òçLãÒLÒÆçMÇÌ9ãÒÜTÍ ÆÇÝ Ì;ÇÁMËLÄLãÅR×jØ;ØÙ â ÉKÁ¼ÇKÆ$ÅÜ ã=¾ÇÜ~¿Ä;Ì9ÒMÇ9ÀÒ1× ßKÝ;Ì ÇÁÇKã ß ½çLãÒLÒLÆ ç;Ç ÌãLÒÜÍLÆMÇ=Ý;ÌÇÁÇ=ã1×ØLØÙ å þ Âã9¾Çu¿¾ÇòÇ$Î ÆòÞ ÃÇ$ÆÂãLËòËLÀLÌÍ ÎÇ æ »L»Æ Ã;À=¾ ÃMÇÆéÇKÎ Æÿ¿ÃÄLÃ9ÅÆMÇKÆ;Ľñ ;à ï ÉË;ÀÌ9Í9ÎÇ=ñKÁ9¿ÆÏàMÌ;¼ÇÓËLÀLÌ ÍÎÇL¼ÿÔíã9¾Ç¿M¾ÇÜÍLÆÇ-Ïü-Ï ÀÌ;¼LÇKý;ÀLÌ Í9ÎÇL¼×ØÙ ó ;ÃÇ$Æ ýã Ä$ÅÃMǽÞL˽ Ô MÃ;ÇKÆýLãÄ$ÅÃ;ÇÜÍLÆÇ ;Ã;ÇKÆÑ$Ò¼LÇKÃ;Ò çLÆ1×ØÙ Ì ·Ë ÀÌ9ÍLÎÇL¼Ü3¼LÌ KÆ1×ØÙ Ì Øêú ËLã Ä × ÌÒÇ ÌòÔëä Ù ºä É9Ë À Ì=ÍÎÇ=ñ=Á9¿MÆ Ë;ÀÌ9ÍÎÇÔ Ë ÀLÌ9ÍÎÇ¼Ü Í;ÆÇ9ÉËLÀ Ì9Í9ÎÇKñ Á=¿Æ.×yÌMØ Ù ºº É$Á¼ Ç$ÆKÅRÜ ã=¾ÇÜ@¿Ä Ì9ÒÇ À9Ò1×Þ;Ë2Ü ËLãLÄ=ÅÃMÇ2×yË ÀLÌ9ÍÎÇÜÍ ÆMÇ=ý À=Þ;ÃMÇÆ1×ØLØLØÙ ºKÈ û º=Ú º â »L»ÆLÒÞëÇÎ Æ çãLÒLÒÆ çÇ=Ìã;ÒéÇ=ãéÇ$Î Æ É ð¼Á¼LÇKÆ$Å º å ÅÝ;ã9ÒLÒÆ;çMÇ=Ìã;ÒÜTÞMÌ;¼KçLãLÒÒLÆçMÇ2×Ø Ù SAP AG 2004 The instance of the generated output class returned when the function module is called contains all the exporting, changing, and table parameters defined in the function module. The type-secure getter methods also contained in this class can be used to evaluate these parameters. The table parameters are also available as Java lists, whereby a list represents a table parameter. The indexed getter methods of such lists return individual rows on the tables. © SAP AG JA100 8-26 6XPPDU\ <RXVKRXOGQRZEHDEOHWR z ,QVWDOOWKH6$3-DYD&RQQHFWRU z &UHDWHDQ5)&FRQQHFWLRQWRDQ6$3V\VWHP z &DOODUHPRWHFDSDEOHIXQFWLRQPRGXOHLQDQ6$3V\VWHP XVLQJWKH-&R z *HQHUDWHSUR[\FODVVHVWRXVHWKH6$3 (QWHUSULVH&RQQHFWRU z &DOODUHPRWHFDSDEOHIXQFWLRQPRGXOHXVLQJD JHQHUDWHGSUR[\ SAP AG 2004 © SAP AG JA100 8-27 © SAP AG JA100 8-28 ([HUFLVH 8QLW ,QWURGXFWLRQWR6$3&RQQHFWLYLW\ 7RSLF 6$3-DYD&RQQHFWRU At the conclusion of this exercise, you will be able to: • Use the SAP Java Connector to call a remote-capable function module from a Java application 6DPSOHVROXWLRQ: 3URMHFW 6WDUW8S.LW 3DFNDJH FRPVDSWUDLQLQJMFRVRO 3UHOLPLQDU\FRQVLGHUDWLRQV In this exercise, you will get information on a flight connection from an SAP system and output it on the console. Call the remote-capable function module 63)/,B*(7'(7$,/ from your Java application. This function module requires as an import parameter the key values of a flight connection from the table VSIOL. For the key passed, the function module selects the complete record from the VSIOL and returns it to the caller via the export interface. You can carry out this exercise using the following subtasks or create an appropriate application “ freestyle.” 1-1 1-2 The SAP Java Connector required for the exercise is already installed on your computer. You only have to install the jar file with the classes belonging to the JCo API (sapjco.jar) in the classpath variable of your 0\3URMHFW project. Your course instructor can tell you where you will find this file in the directory structure of your computer. In your 0\3URMHFW project, create a new package with the name FRPVDSWUDLQLQJMFRH[F. In this package, define the class -&R6SIOL*HW'HWDLO and create in it the attributes and methods from the UML diagram shown. Note that all components of the class -&R6SIOL*HW'HWDLO are static. © SAP AG JA100 8-29 1-3 1-4 1-5 1-6 The static method FRQQHFW7R6$3 uses the values passed to set up a direct connection to the SAP system. To create a -&2&OLHQW object here, use the attribute P&RQQHFWLRQ created in step 1-2. If the connection setup is successful, the method should create a -&25HSRVLWRU\ instance using the attribute P5HSRVLWRU\ and should return the value WUXH. If an exception occurs during the connection setup, the method FRQQHFW7R6$3 should return the value IDOVH The static method GLVFRQQHFW)URP6$3 is for ending an existing connection to the SAP system. Use the instance method GLVFRQQHFW from the class -&2&OLHQW. The private static method FUHDWH)XQFWLRQ takes the name of an RFC function module as a VWULQJ and returns the related Java representative as an object of the class -&2)XQFWLRQ. If no -&2)XQFWLRQ instance can be created, then the method returns the value ]HUR. The static method VKRZ&RQQHFWLRQ'HWDLOV is for outputting on the console detailed information for the flight connection key passed to it. Call the remote-capable function module 63)/,B*(7'(7$,/ from it. First familiarize yourself with the interface of this function module in the SAP system. 1-6-1 1-6-2 1-6-3 1-6-4 © SAP AG Call the method FUHDWH)XQFWLRQ from the method VKRZ&RQQHFWLRQ'HWDLOV to create a Java representative for the function module. Reference the created representative via the static attribute IXQFWLRQ created in step 1-2. Specify the values for the import parameters of the function module. First, call the method JHW,PSRUW3DUDPHWHU/LVW for the -&2)XQFWLRQ object to be able to access the import parameters of the function module. For the returned object of the type -&23DUDPHWHU/LVW, you can then call the method VHW9DOXH to supply the two elementary import parameters of the function module with the values received via the interface from VKRZ&RQQHFWLRQ'HWDLOV . Call the function module in the SAP system and evaluate the 5(7851 parameter. Ensure that this structure in the component 7<3( contains the value “ S” or the initial value. If this component contains a different value, an error occurred during the execution of the function module in the SAP system. In this case, you trigger an exception in your Java application. Lastly, output the connection details on the console. Access the export parameter &211(&7,21 of the function module. Output on the console a number of selected components of this structure. JA100 8-30 1-7 1-8 In the same packagecreate the class -&R7HVW for testing. The class should contain a PDLQ method. Call the method FRQQHFW7R6$3 . Your course instructor will provide you with the necessary system information. 1-7-1 If the connection was set up successfully, call the method VKRZ&RQQHFWLRQ'HWDLOV . You can choose any flight connection key to be passed here (for example, “ LH” for the airline company and “ 400” for the connection number). 1-7-2 Finally end the connection with the SAP system by calling the method GLVFRQQHFW)URP6$3 . Test your application. © SAP AG JA100 8-31 © SAP AG JA100 8-32 6ROXWLRQ 8QLW ,QWURGXFWLRQ6$3&RQQHFWLYLW\ 7RSLF 6$3-DYD&RQQHFWRU LPSRUW com.sap.mw.jco.IFunctionTemplate; LPSRUW com.sap.mw.jco.JCO; SXEOLF FODVV JCoSpfliGetDetail { SULYDWH VWDWLF JCO.Client mConnection = QXOO; SULYDWH VWDWLF JCO.Function function = QXOO; SULYDWH VWDWLF JCO.Repository mRepository = QXOO; //Connect to SAP SXEOLF VWDWLF ERROHDQ connectToSAP( String client, String user, String passwd, String lang, String appServer, String sysNo) { WU\ { mConnection = JCO.createClient( client, //SAP client user, //userid passwd, //password lang, //language appServer, //app server host name sysNo); //system number mConnection.connect(); mRepository = QHZ JCO.Repository("JA100", mConnection); } FDWFK (Exception e) { e.printStackTrace(); UHWXUQ IDOVH; } UHWXUQ WUXH; © SAP AG JA100 8-33 } //Call Remote Function Module SXEOLF VWDWLF YRLG showConnectionDetails(String carrid, String connid) { function = JCoSpfliGetDetail.createFunction("SPFLI_GETDETAIL"); LI (function == QXOO) WKURZ QHZ RuntimeException( "Remote Function Module not found"); //Supply the import parameters of the RFM JCO.ParameterList im_param = function.getImportParameterList(); im_param.setValue(carrid, "CARRID"); im_param.setValue(connid, "CONNID"); mConnection.execute(function); //Analyze the export parameters of the RFM JCO.ParameterList ex_param = function.getExportParameterList(); JCO.Structure returnStruc = ex_param.getStructure("RETURN"); LI (!(returnStruc.getString("TYPE").equals("") || returnStruc.getString("TYPE").equals("S"))) { WKURZ QHZ RuntimeException( returnStruc.getString("MESSAGE")); } JCO.Structure connStruc = ex_param.getStructure("CONNECTION"); System.out.println("Carrid: " + connStruc.getString("CARRID")); System.out.println("Connid: " + connStruc.getString("CONNID")); System.out.println("Cityfrom: " + connStruc.getString("CITYFROM")); System.out.println("Cityto: " + connStruc.getString("CITYTO")); System.out.println( "Distance: " + connStruc.getString("DISTANCE") + " " + connStruc.getString("DISTID")); } © SAP AG JA100 8-34 //Disconnect from SAP SXEOLF VWDWLF YRLG disconnectFromSAP() { mConnection.disconnect(); } //Create instances of class JCO.Function SULYDWH VWDWLF JCO.Function createFunction(String name) { IFunctionTemplate ft = mRepository.getFunctionTemplate(name.toUpperCase()); LI (ft == QXOO) UHWXUQ QXOO; UHWXUQ ft.getFunction(); } } SXEOLF FODVV JCoTest { SXEOLF VWDWLF YRLG main(String[] args) { LI (JCoSpfliGetDetail .connectToSAP("xxx", "xxxxxxx", "xxxxxxx", "xx", "xxxx", "xx")) { JCoSpfliGetDetail.showConnectionDetails("LH", "400"); JCoSpfliGetDetail.disconnectFromSAP(); } } } © SAP AG JA100 8-35 © SAP AG JA100 8-36 ([HUFLVH 2SWLRQDO 8QLW ,QWURGXFWLRQWR6$3&RQQHFWLYLW\ 7RSLF 6$3(QWHUSULVH&RQQHFWRU At the conclusion of this exercise, you will be able to: • Use the SAP Enterprise Connector to call RFC-capable function modules in the SAP system using Java proxies 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJHFRVRO 3UHOLPLQDU\FRQVLGHUDWLRQV In the last exercise, we called the remote-capable function module 63)/,B*(7'(7$,/ using the native application of the SAP Java Connector to display detailed information for a flight booking on the console. In this exercise you will implement the same scenario using the SAP Enterprise Connector. You can carry out this exercise using either the following tasks or an application of your choice. 2-1 2-2 2-3 First make sure that the following jar files needed for using the SAP Enterprise Connector are in the classpath variables of your 0\3URMHFW project: aii_proxy_rt.jar, aii_util_misc.jar, SAPmdi.jar, and sapjco.jar. Your course instructor can tell you where you will find these files in the directory structure of your computer. In your 0\3URMHFW project, you now create a new package with the name FRPVDSWUDLQLQJHFRH[F. Call the wizard installed in the development environment to generate a proxy for the function module 63)/,B*(7'(7$,/. Your course instructor will provide you with the information required for logging on to the SAP system. Store the generated classes in the package FRPVDSWUDLQLQJHFRH[F. Give the proxy class the name 6SIOL3UR[\B3RUW7\SH. Switch to the package FRPVDSWUDLQLQJHFRH[F and create the class (&R6SIOL*HW'HWDLO. In this class, define the attributes and methods from the UML diagram shown. You can copy the relevant passages of the class -&R6SIOL*HW'HWDLO from the previous exercise. © SAP AG JA100 8-37 2-4 2-5 2-6 The method FRQQHFW7R6$3 largely corresponds to the method of the same name from the class -&R6SIOL*HW'HWDLOfrom the previous exercise. Using the values passed, it sets up a conenction of the type 'LUHFW&RQQHFWLRQ to the SAP system. To create a -&2&OLHQW object here, use the static attribute P&RQQHFWLRQ created in step 2-3. If the connection setup is successful, the method should return the value WUXH. If an exception occurs during the connection setup, the method FRQQHFW7R6$3 should return the value IDOVH The method GLVFRQQHFW)URP6$3 can be taken completely from the class -&R6SIOL*HW'HWDLO. This is to end an existing connection to the SAP system. The method VKRZ&RQQHFWLRQ'HWDLOV is for outputting detailed information on a flight connection on the console by calling the function module 63)/,B*(7'(7$,/. In contrast to the previous exercise, the function module in this exercise is called using the generated proxy class. In the method VKRZ&RQQHFWLRQ'HWDLOV , first create an object of the class generated by the wizard, 6SIOLB*HWGHWDLOB,QSXW, which represents the import interface of the function module. For this object, call the methods VHW&DUULG and VHW&RQQLG to specify values for the import parameters. Pass these methods the values received by VKRZ&RQQHFWLRQ'HWDLOV via the interface. 2-6-1 2-6-2 2-6-3 © SAP AG Create an object of the generated proxy class 6SIOL3UR[\B3RUW7\SH and supply it with a connection object. Use the -&2&OLHQW instance referenced by the attribute P&RQQHFWLRQ. Use the instanced proxy object to call the function module in the SAP system. Pass to the method VSIOLB*HWGHWDLO the representative of the import interface named above and accept an object of the generated class 6SIOLB*HWGHWDLOB2XWSXW. Catch any exception of the types 6\VWHP)DXOW([FHSWLRQ or $SSOLFDWLRQ)DXOW([FHSWLRQ that occur during the call. With the object of the class 6SIOLB*HWGHWDLOB2XWSXW returned when the function module is called, you gain access to the export interface of the function module. Evaluate the 5(7851 parameter from this. Call the method JHW5HWXUQ for the 6SIOLB*HWGHWDLOB2XWSXWobject returned. You obtain an object of the generated class %DSLUHW7\SH, which provides you with get methods for accessing the individual component values of the 5(7851 structure. Ensure that the 5(7851 structure in the component 7<3( contains the value “ S” or the initial value. If this component contains a different value, an error occurred during the execution of the function module in the SAP system. In this case, you trigger an exception in your Java application. JA100 8-38 2-6-4 2-7 2-8 Lastly, output the connection details on the console. Use the method JHW&RQQHFWLRQ and the object 6SIOLB*HWGHWDLOB2XWSXW to access the export parameter &211(&7,21 of the function module. You will obtain an object of the generated class 6SIOL7\SH, which provides you with get methods for accessing the individual component values of the &211(&7,21 structure. Output on the console the content of a number of selected components of this structure. In your packagecreate the class (&R7HVW for testing. The class should contain a PDLQ method. In this, call the method FRQQHFW7R6$3 . Your course instructor will provide you with the necessary system information. 2-7-1 If the connection was set up successfully, call the method VKRZ&RQQHFWLRQ'HWDLOV . You can choose any flight connection key to be passed here. 2-7-2 Finally, end the connection with the SAP system by calling the method GLVFRQQHFW)URP6$3 . Test your application. © SAP AG JA100 8-39 © SAP AG JA100 8-40 6ROXWLRQ 2SWLRQDO 8QLW ,QWURGXFWLRQWR6$3&RQQHFWLYLW\ 7RSLF 6$3(QWHUSULVH&RQQHFWRU LPSRUW com.sap.aii.proxy.framework.core.ApplicationFaultException; LPSRUW com.sap.aii.proxy.framework.core.SystemFaultException; LPSRUW com.sap.mw.jco.JCO; SXEOLF FODVV ECoSpfliGetDetail { SULYDWH VWDWLF JCO.Client mConnection = QXOO; //Connect to SAP SXEOLF VWDWLF ERROHDQ connectToSAP( String client, String user, String passwd, String lang, String appServer, String sysNo) { WU\ { mConnection = JCO.createClient( client, //SAP client user, //userid passwd, //password lang, //language appServer, //app server host sysNo); //system number mConnection.connect(); } FDWFK (Exception e) { e.printStackTrace(); UHWXUQ IDOVH; } UHWXUQ WUXH; } //Call Remote Function Module via Enterprise Connector © SAP AG JA100 8-41 SXEOLF VWDWLF YRLG showConnectionDetails(String carrid, String connid) { //Supply the import parameters of the RFM Spfli_Getdetail_Input input = QHZ Spfli_Getdetail_Input(); input.setCarrid(carrid); input.setConnid(connid); //Supply the proxy instance with the JCO.Client instance SpfliProxy_PortType proxy = QHZ SpfliProxy_PortType(); proxy.messageSpecifier.setJcoClient(mConnection); Spfli_Getdetail_Output output = QXOO; WU\ { output = proxy.spfli_Getdetail(input); } FDWFK (SystemFaultException e) { e.printStackTrace(); System.exit(1); } FDWFK (ApplicationFaultException e) { e.printStackTrace(); System.exit(1); } //Analyze the export parameters of the RFM Bapiret2Type returnStruc = output.getReturn(); LI (!(returnStruc.getType().equals("") || returnStruc.getType().equals("S"))) { WKURZ QHZ RuntimeException(returnStruc.getMessage()); } SpfliType connStruc = output.getConnection(); System.out.println("Carrid: " + connStruc.getCarrid()); System.out.println("Connid: " + connStruc.getConnid()); System.out.println("Cityfrom: " + connStruc.getCityfrom()); System.out.println("Cityto: " + connStruc.getCityto()); System.out.println( "Distance: " + connStruc.getDistance() + " " + connStruc.getDistid()); } //Disconnect from SAP SXEOLF VWDWLF YRLG disconnectFromSAP() { mConnection.disconnect(); } } © SAP AG JA100 8-42 SXEOLF FODVV ECoTest { SXEOLF VWDWLF YRLG main(String[] args) { LI (ECoSpfliGetDetail .connectToSAP("xxx", "xxxxxxx", "xxxxxx", "xx", "xxxxx", "xx")) { ECoSpfliGetDetail.showConnectionDetails("LH", "400"); ECoSpfliGetDetail.disconnectFromSAP(); } } } © SAP AG JA100 8-43 © SAP AG JA100 8-44 -((3UHYLHZ &RQWHQWV z &UHDWLQJJUDSKLFXVHULQWHUIDFHV z $SSOHWV z -DYD(QWHUSULVH(GLWLRQ SAP AG 2004 © SAP AG JA100 9-1 8QLW2EMHFWLYHV $IWHUFRPSOHWLQJWKLVXQLW\RXZLOOEHDEOHWR z 1DPHWKHWRRONLWVRIWKH-DYD6WDQGDUG(GLWLRQIRUWKH FUHDWLRQRIJUDSKLFXVHULQWHUIDFHV z 'HVFULEHWKHVWUXFWXUHRI-DYD(QWHUSULVH(GLWLRQ z 1DPH6$3VSHFLILFHQKDQFHPHQWVWR-(( SAP AG 2004 © SAP AG JA100 9-2 &UHDWLQJ*UDSKLFDO,QWHUIDFHV8VLQJ-6'. 7KH-DYDSODWIRUPVWDQGDUGHGLWLRQRIIHUVWZROLEUDULHVIRUFUHDWLQJJUDSKLFDO XVHULQWHUIDFHV z $:7 $EVWUDFW:LQGRZLQJ7RRONLW z 6ZLQJ SAP AG 2006 Unlike most other programming languages, right from the start, Java was developed with the aim of offering a versatile, but user-friendly system for configuring graphical interfaces. The result of these endeavors has been available since JDK 1.0 in the form of a graphic library called $EVWUDFW :LQGRZLQJ7RRONLW ($:7). In addition to the $:7, there is a second library for configuring graphical user interfaces. It is called 6ZLQJ and has been available as an add-on as of JDK 1.1 and as a fixed part of the Java Development Kit as of Version 1.2. Since 6ZLQJ applications offer way more options than $:7, most GUI programs today are written using 6ZLQJ. © SAP AG JA100 9-3 *UDSKLF8VHU,QWHUIDFHV([DPSOH !#"$%&%"'()( *)+$,-./10 243 5$16' 7!/ 8 9/):71;$/"1<=$>,? 7!;$1/"<A@ ,/+ 89)/>:7!;$1/"<CBED FHG 5$16' 7!/ )8 I'? />"J2) 7K>L7?I>'?/>"M@ ,/+ 81I'N /"OBPFG 5$16' 7!/ )8 Q7712,M>7)72,&@ ,)/+ 8Q77!2),CB R()'S&T/""2#R FHG >1#")$%A(7'7$)%M6>2>$1< L 0 '$),OB*>7!5>$,-CUWVX')5)-(F43 *1+>$),-./102Y</?02J@ , /+ *!+$1,-). /!0 2CBPFG Z >1#")$% *1+ $,-)./?02OBEF[3 8;5)'?0/]\5'N0 /Y@ , /+ 8;5)'!0 /^B RP0>S_7$7)"/`R FG \5'N0 /bac-/ 7!d2),7?/,7>e',/CBcFLaf(!/7!I'1S 217gB ,/+ h5$)<I'1S#2 7iBjlkPjgkfmnokpm1nFF`G \5'N0 /bac-/ 7!d2),7?/,7>e',/CBcFLac')<<OB ,/+ 81I'!#/"iB RPq#'?0/ir?R FFG \5'N0 /bac-/ 7!d2),7?/,7>e',/CBcFLac')<<OB$,1>7!;$)/ ")< FHG \5'N0 /bac-/ 7!d2),7?/,7>e',/CBcFLac')<<OB #7)712,FLG \5'N0 /bac-/ 7!d2),7?/,7>e',/CBcFLac')<<OB2#7p 7!I>'1/"FG 7)712,CaE')<<Ns#% 71$)2, I$(7?/,)/>5CB ,/+ s%71$)2,>I$(7?/,/5CBfFt3 )#"$)%M62$< ')% 7$2),e)/5\2)5?0/)<OB s#% 7$2,u6>/,7Y/)6F[3 2 7K 7!I')/"gaP(!/79)/>:7gB R?v/>")")24R w&$),!>7;$)/"<oax-/719>/): 7iBcFFHG Z Z FHG Z Z \5'N0 /ba'%)yCBcFLG \5'N0 /bap(!/ 7!I2%'>7$2,CBcz{){Lkcj {{ FHG \5'N0 /bap(!/ 7!|)/ ()$}1'N`"1/~B \)'"(1/ FlG \5'N0 /bap(!/ 7K$>()$#"1/B 75/ FG SAP AG 2004 © SAP AG JA100 9-4 $SSOHWV $SSOHW $QDSSOHWLVH[HFXWHGLQWKH:HEEURZVHU WKHDSSOHWFDQQRWUXQRQLWVRZQ :HEEURZVHU LQVWDQWLDWHVFODVV 1RDFFHVVWRORFDO ILOHV &DQQRWVWDUWH[WHUQDO SURJUDPV $OZD\VGHULYHGIURP WKHDSSOHWFODVV !! c $OZD\VHYHQWDQG JUDSKLFVRULHQWHG ,QFOXGHGLQ+70/ SAP AG 2004 Applets are included in HTML pages. They require a Web browser to be executed. The browser loads the applet to its main memory via the Internet and then executes it. Applets are always graphics-oriented and event-oriented. © SAP AG JA100 9-5 $SSOHW([DPSOH '%y')-)/ %)2?0~aW(1'~aP715'$,>$1,-CaE<)/!02G $0#2)57 '16>'oaE'?#"1/ 7las")/#7`G $0#2)57 '16>'oaE'+H7lah5'?T$% (lG >1")$)%Y%>"'(( s "/7N./!0 2 /: 7!/,< ( s #"/ 7_3 Z "$%Y62$< H'$1, 7iBh5'N T$%>(-F_3 -iaE<5'+*>75$1,-OB RNv$`kX'?0['),s #"/ 7R km){k{>FHG Z v)9! I) v)uNs .> 9 19IuNs>L"1/ 7X./!0 2 L 9 !9)I)u L vu?s. Q)). vm1Ns")/ 7M./!02 H vm1 see1Iu9Yd).u)@>%2?0~aP(1'!^aW715'$),>$1,-Oax<)/102gas>)#"/ 7N./10 2oax%>"' (( .>9v1@>j>{{Mv)uH?hv9@>n>{! sHe)eIu9 L Q.>) H v9?I SAP AG 2004 © SAP AG JA100 9-6 )URP-6(WR-(( NNKPcKpN¡1¡1¢b i£L¤ fWPpf¥cPN¦ cE§L `E¨ -(( -6( -0( SAP AG 2004 The Java 2 Standard Edition (J2SE) provides a complete environment for the development of applications on desktops and servers. It also forms the basis of the Java 2 Enterprise Edition (J2EE). The Java 2 Enterprise Edition defines a standard for the development of component-based business applications. © SAP AG JA100 9-7 )URP-6(WR-(( &KDUDFWHULVWLFVRI-6(DSSOLFDWLRQV z Stand-alone applications z Generally run locally on a single computer z Each application runs in its own virtual machine -DYD90 -DYD90 $SSOLFDWLRQ $SSOLFDWLRQ SAP AG 2004 The Java virtual machine (VM) provides the runtime environment for Java applications. Each J2SE application runs in its own VM. It is possible to start several VMs on one computer at the same time; however, the applications running in the different VMs cannot communicate directly with each other. © SAP AG JA100 9-8 )URP-6(WR-(( ,QWURGXFWLRQRI-DYD(QWHUSULVH(GLWLRQ Platform for the creation of distributed, secure, and scalable business applications © ª«Hª¬~­ © ª«Hª¬~­ © ª«Hª¬~­ SAP AG 2004 The features of the Java 2 Standard Edition do not fully satisfy the needs of enterprises for distributed, secure, and scalable applications. In 1999, Sun introduced the Java 2 Enterprise Edition to meet these demands. It enables the creation of applications that consist of a series of subcomponents that can be run on different computers. © SAP AG JA100 9-9 'LVWULEXWHG0XOWLSOH7LHU$SSOLFDWLRQVZLWK-(( &OLHQW0DFKLQH Client Tier -((6HUYHU0DFKLQH 'DWDEDVH 6HUYHU 0DFKLQH Web Tier EIS Tier Business Tier Server-side presentation logic Server-side business logic µ²>¶O·1¸¹º»¼ ¹?²³ °®>½¾·1¸>¹?º»¼ ¹1²³ ®¯°° ±1²1³ ´²1³ SAP AG 2004 © SAP AG JA100 9-10 &RPSRQHQWVLQD-(($SSOLFDWLRQ &OLHQW FRPSRQHQWV ÉÈHÊËÊLÌxÆ#Í ÎÈÌ :HE FRPSRQHQWV %XVLQHVV FRPSRQHQWV Ï ÈÌ«gÁ È>ÅÎ ©ª«ª Ï ÈÌ«LÈ#Ì ÐHª ÑHÈÎ ¿^ÀLÀLÁ È>Å ¿^À`ÀLÁàĪ>Åf ÆgÇ ÄÁ ÈHÇ Å Ò Ç ÅxÈÌPÀLÌc ÎÈ ©ª«Lª#ÓlȪHÇ Î µ¾²¶O·¸>¹º»¼ ¹!²³ °®½¾·!¸ ¹?º»¼ ¹?²³ ®)¯°#°±²³ ´²³ SAP AG 2004 J2EE applications are composed of individual components. A J2EE component is an independent software unit which, with its classes and files, is inserted into a J2EE application and can communicate with other components. The J2EE specification defines the following J2EE components: y Application clients and applets are components that run on the client. y Servlets and Java Server Pages are Web components that run on the server. y Enterprise JavaBeans are business components that also run on the server. The difference between J2EE components and “standard” Java classes is that J2EE components are combined to constitute a J2EE application. © SAP AG JA100 9-11 &RQWDLQHU6HUYLFHV 6HUYLFHV Öb»¼ × Ù»)ÚÛ¼ ¹Ø Ü ²³ ´#¼ ·!² Õ ³»¹?±»·Nº¼ ¸¹ Öb²!±!±»)Ø>¼ ¹!Ø ß²³±>¼ ±º²¹!·1² Ü ²·Ý)³¼ ºÃÞ µ¾²¶O·¸>¹º»>¼ ¹1²³ °®>½à·!¸ ¹Nº»>¼ ¹!²³ ®¯)°#°Ô±1²1³ ´²1³ SAP AG 2004 The architecture of J2EE simplifies the creation of applications through the concept of reusable components. Moreover, the J2EE server provides component services in the form of a container for each component type. This simplifies programming as it allows the developer to concentrate exclusively on the problem at hand. Also, recurring problems in application development, such as transaction management and security, are supported by the container. For instance, the J2EE security model can configure a Web component or an Enterprise Bean in such a way that only authorized users may access it. © SAP AG JA100 9-12 -'%& -DYD'DWDEDVH&RQQHFWLYLW\ The JDBC API can be used to implement database access. ä ®>åL½#æ â㠵ᲶO·¸>¹º»>¼ ¹!²³ °>®½à·1¸¹Nº»¼ ¹!²³ ®¯°°Ô±²1³ ´>²1³ SAP AG 2004 In J2EE, the Java Database Connectivity (JDBC) API enables access to databases. This API can be used by JavaBeans and by servlets and JSPs for the processing of SQL instructions. © SAP AG JA100 9-13 6$36SHFLILFV 3ULQFLSDO6$3VSHFLILFHQKDQFHPHQWVWRWKH-((VSHFLILFDWLRQ ç Web Dynpro as user interface ç Open SQL for Java ç Version management ç ç Component Build Service Transport management "! # $%#'& (!*) $"+% ,/L ÌÆ ÉÈþ Ê. NÇ`ÿ ÀL ý!Ï þÈ#ÿ Ì«þ Á È>Å © pÏ ýÐ è1pK¤ é!cPlê ëP¥ff û éN¦ Pü! ëK¦ ¤ Ké ê ëW¥fW þ ý!þÿ cþ 0 1& #2 !43% ©5~ , Ó76 Ï/9*: © 8 ÀÈ#Ç Ï/9;: ìíNîgïí?ðfñKðfò ólô ðlõ öP÷ø1ø õ ïNïNù ô ú õ òÃô í ð SAP AG 2004 'HYHORSPHQWHQYLURQPHQW In some cases, the J2EE specification is not sufficient for creating large business applications that can be scaled and ported. The topic of persistence is important in this regard. To this purpose, SAP has made enhancements to the J2EE standard, such as the introduction of Open SQL for Java, which makes it possible to program SQL instructions independently of the underlying database management system. With the Web Dynpro, SAP has introduced its own technology for creating user interfaces. With the NetWeaver Development Infrastructure, SAP provides version management (Design Time Repository), Build Service (Component Build Service) as well as transport management (Change Management Service). © SAP AG JA100 9-14 6XPPDU\ <RXVKRXOGQRZEHDEOHWR z 1DPHWKH7RRONLWVRIWKH-DYD6WDQGDUG(GLWLRQIRUWKH 1DPHWKHWRRONLWVRIWKH-DYD6WDQGDUG(GLWLRQIRUWKH FUHDWLRQRIJUDSKLFXVHULQWHUIDFHV FUHDWLRQRIJUDSKLFXVHULQWHUIDFHV z 'HVFULEHWKHVWUXFWXUHRIWKH-DYD(QWHUSULVH(GLWLRQ z 'HVFULEHWKHVWUXFWXUHRI-DYD(QWHUSULVH(GLWLRQ z 1DPHWKH6$3VSHFLILFHQKDQFHPHQWVWRWKH z 1DPH6$3VSHFLILFHQKDQFHPHQWVWR-(( -((VSHFLILFDWLRQ SAP AG 2004 © SAP AG JA100 9-15 © SAP AG JA100 9-16 $SSHQGL[ &RQWHQWV z )XUWKHULQIRUPDWLRQDERXWWKH6$3-DYD&RQQHFWRU z ,QWHUQDWLRQDOL]DWLRQ z 2EMHFWVHULDOL]DWLRQ z $FFHVVWRILOHV z 7KHMDYDXWLO6WULQJ7RNHQL]HU FODVV SAP AG 2004 © SAP AG JA100 10-1 &UHDWLQJD-&2&OLHQW,QVWDQFH $PRQJRWKHUVWKHIROORZLQJRYHUORDGHGYHUVLRQVRIWKHPHWKRG FUHDWH&OLHQW DUHDYDLODEOH /RDG GLVWULEXWLRQ SXEOLFVWDWLF-&2&OLHQWFUHDWH&OLHQW 6WULQJ FOLHQW6WULQJ XVHU 6WULQJSDVVZG6WULQJ ODQJ 6WULQJFUHDWH PVKRVW6WULQJ UQDPH 6WULQJ&OLHQW JURXS $YRLGKDUGFRGHGV\VWHPDQGXVHU LQIRUPDWLRQ SXEOLF VWDWLF -&2&OLHQW FUHDWH&OLHQW MDYDXWLO3URSHUWLHV SURSHUWLHV SAP AG 2004 There are several overloaded versions of the method createClient( ) from the JCo class used for creating JCO.Client objects. In the main part of this course, a version was used that leads to connection with a particular application server. There is also a variant that enables logging on to a server group via load balancing, as well as a version that receives the required logon data in the form of an object of the class java.util.Properties. With these versions in particular, it is possible to avoid hard-coded system and user information in Java programs. Depending on the release status of the SAP system, logon via Single Sign-On and X509 certificates may also be supported. You can find further details on the method createClient( ) in the corresponding API documentation. © SAP AG JA100 10-2 2EWDLQLQJ &RQQHFWLRQ ,QIRUPDWLRQ P&RQQHFWLRQ SYSID: T70 CLIENT: 400 USER: TRAINER LANGUAGE: E ISO_LANGUAGE: EN OWN_CODEPAGE: 1100 OWN_CHARSET: ISO8859_1 OWN_ENCODING: ISO-8859-1 OWN_BYTES_PER_CHAR: 1 PARTNER_CODEPAGE: 1100 PARTNER_CHARSET: ISO8859_1 PARTNER_ENCODING: ISO-8859-1 PARNER_BYTES_PER_CHAR: 1 PARTNER_REL: 46C 2EWDLQLQJ FRQQHFWLRQ LQIRUPDWLRQ 6\VWHPRXWSULQWOQ P&RQQHFWLRQJHW$WWULEXWHV P&RQQHFWLRQGLVFRQQHFW SAP AG 2004 After the connection has been established, the Remote Function Call (RFC) attributes of the established connection can be queried. You do this by calling the method getAttributes( ) for JCO.Client object. This method returns an object of the class JCO.Attributes. You can find details on the individual connection characteristics in the API documentation for this class. © SAP AG JA100 10-3 &RQQHFWLRQ6HWXSYLD&RQQHFWLRQ3RROLQJ -DYD Connection setup via connection pooling 3RRO0DQDJHU P&RQQHFWLRQ Manages the connection pools Connection object is requested from a connection pool ! G Connection pool: Maximum no. of connections: Client Userid: Password: Language: Appl. server: System number: 3RRO !#"$&% !&>?"@A ' Connection pool: Maximum no. of connections: B (*)+) ,.-/102 34 56- 7!,-8 -3 2 9:06;<'+)<=*) )<) Client Userid: Password: Language: Appl. server: System number: (C)<) 71D/13412E34 F2E,/71"C-&3 2 9:0;+'+)+=<) )+) 3RRO SAP AG 2004 In addition to a direct connection, it is also possible to establish a connection via connection pooling. This type of connection setup is particularly suitable for Web applications. When working via connection pooling, the connection object (object of the class JCO.Client) is not generated by using static method createClient( ) from the JCo class as it is with a direct connection, but is requested from a connection pool. The above example shows two connection pools, represented in the program via objects of the class JCO.Pool. Each connection pool has a name (here, MY_POOL_1 and MY_POOL_2) by which it can be addressed in the program. In principle, any name can be chosen. It is important to remember, however, that pool objects are available for all applications within the virtual machine. Consequently, different applications that run within the same virtual machine must be named in such a way that they will not be confused with each other. When a pool object is generated in the program, the maximum number of connection objects from this pool that can be used simultaneously is specified. This value cannot be changed later and should be calculated so as to be adequate for the application. When a pool object is created, in addition to the pool name and the maximum number of connections, system information such as user and client is also transferred. All connection objects from a pool therefore represent connections to the same system with the same user. If, for authorization reasons, more than one user is needed, a Java program can work with several connection pools. All connection pools within a virtual machine are managed via the pool manager, which is an object of the class JCO.PoolManager. © SAP AG JA100 10-4 3RRO0DQDJHPHQW8VLQJWKH3RRO0DQDJHU -&R VLQJOHWRQ UHWXUQV WKH 3RRO0DQDJHU LQVWDQFH JHW3RRO 6WULQJ UHWXUQVWKHSRROZLWKWKHVSHFLILHG QDPHRUQXOOLIWKDWSRROGRHVQRW H[LVW JHW&OLHQW 6WULQJ UHWXUQVDFRQQHFWLRQIURPWKH VSHFLILHGSRRO -&R 3RRO0DQDJHU singleton(): JCO.PoolManager getPool(String): JCO.Pool getClient(String): JCO.Client releaseClient(JCO.Client): void ... UHOHDVH&OLHQW UHWXUQVWKHFRQQHFWLRQWRWKHSRROWKDW ZDVVSHFLILHG H&HJI KLM N K&OQPSR T.U U 3RROPDQDJHU SAP AG 2004 The class JCO.PoolManager is a singleton with which the PoolManager object can be queried from this class via the static method singleton( ). Via the instance method getPool( ), which you call along with the PoolManager object, you receive access to the connection pool, whose name you enter when calling via the interface. If there is no existing pool with the specified name, the method returns null. If, in a Java program, you need a connection to the SAP system, you request this using the method getClient( ) via the pool manager from a connection pool whose name you specify on the interface. When the connection is no longer required, you return it to the pool using releaseClient( ). © SAP AG JA100 10-5 &UHDWLQJD&RQQHFWLRQ3RRO -&R &UHDWLQJDFRQQHFWLRQSRROIRUDQ6$3 V\VWHPYLD-&2DGG&OLHQW3RRO 7KHUHDUHVHYHUDORYHUORDGHGYHUVLRQV RIWKHPHWKRG-&2DGG&OLHQW3RRO -&R 3RRO 3RRO getMaxPoolSize(): int getMaxWaitTime(): long setMaxWaitTime(long): void getMaxUsed(): int ... HH I K&LQM N KO P RT.U&U Connection pool: Maximum no. of connections: V V V Client: Userid: Password: Language: ... VVV VVV VVV SAP AG 2004 The getClient( ) method from the class JCO.PoolManager either returns an existing connection to the SAP system from the pool or generates a new one, provided that all previously pooled connections are being used and the maximum number of connections has not been reached. If all connections in the pool are being used and the pool has reached its maximum size when getClient( ) is called, the SAP Java Connector has to wait until a connection is free. If no connection is available over a lengthy period of time, the JCo triggers an exception with the error type JCO.Exception.JCO_ERROR_RESOURCE. The default wait time is 30 seconds. This value can be changed using the method setMaxWaitTime(), which can be called for the pool manager as well as for any JCO.Pool object. The new value is passed in milliseconds. © SAP AG JA100 10-6 &RQQHFWLRQ 3RROLQJ([DPSOH É# # W XQY*Z [Q\ ] ^+_YZC`ba+cQcdfegChijlk mniope>a+cQcdpeWm q rts+uCcFvwaCxQx\pi&[ ZQ[C`Qy_{z[QZ[ `Cy_|k}s+uCc~vaCxQx\fi[CZQ[C`y_!v*Y+ZQ`\+y^+xCZFq ^<_+ s*uCc?vaCxxQ\&xQx\kz[CZ[*`y_!v`y^*aCxQxQ\Fa<cQcdpegQhij&q YCX E&xxQ\kQk Z*\Q\ {Z[<zy s*u c#vw[QCQu \CYCyQZ^+aCxQx\?a+ccdpe gChQi&j! z&[Cpe6QxCZCZQy ^*Y*xQZ m Q m \Y+yZ^ mp h6¡$gjC.m &+yQ_ W mp¢cQc C£ hddm &[C*¤ Connection setup WQW m@¥jm \C[QZC` [C`Cy via connection W+r m*¡p¦¥ ¢ C m [<§xQ^ pooling W* m m .q lp Z_ W ¨ W s*uCc?vu \Y+yQZ^©zuQxQZQZyQ^*Y*xQZ|kz&[CZ[C`Cy _v`Qy^<u\Y*yCZ^#ªaQcQcdfe gQhQijq W ]<Q^<y<z«vx*&^>v¬&_QYCZ^\+Z­Ezu xCZCZQy^*YCxCZvw`Qy^$h1^Q^<_ Yp® &^+yFQq W ¯¨ C[^+*§ j* Cy<.^*Y*xQZ}y° WQ y#v¬._QY*Z^*] ^+[CQ±_C[QCy­.q W ¨ XQY*Z[\Q\< r z&[CZ[*`Qy_vw_Cy\Cy[ yQu \QY*yQZ^¬zuxCZQZCy ^+YCx Z&q rW ¨ Connection pool: Maximum no. of connections: Client Userid: Password: Language: Appl. server: System number: ²f³´µ¶f¶ ·¸´¹ º »¼¼ ½w¾¿pÀ ÁÂþ Ķp¶f½Åÿ$·Ã· Æ$ À Ç6ÆĪº¼¬È¬¼ ¼¬¼ SAP AG 2004 In the above example for connection pooling, a pool with the name MY_POOL_1 is used. In line 1, the name is stored in a constant and in line 2, the pool manager is instantiated from the class JCO.PoolManager using the static method singleton( ). The getPool( ) method, which you call for the pool manager, returns a reference to the connection pool with the name MY_POOL_1 if a pool with that name exists. If the method returns null, you know that there is no pool with this name and that you can create one of that name without running any risks. You generate a pool by calling the static method addClientPool( ) from the class JCO. You enter the pool name, system, and user information, as well as the number of connections for the pool. Like in connection setup via direct connection, connection pooling also has variants for the generation of instances. So here, too, through method overloading, it is possible to perform load balancing as well as the transfer of system and parameter information in the form of an object of the class java.util.Properties. Using the getClient( ) method, you request a connection from the connection pool and receive a JCO.Client object that represents the connection to the SAP system. In contrast to connection setup via direct connection, in connection pooling you do not call the method connect( ) to JCO.Client instance. The connection to the SAP system is already established, so you can proceed directly to it and have the attributes of this connection displayed on the console. After calling getAttributes( ), return the connection to the pool using releaseClient( ). It makes sense to implement this in the final block; in this way, the connection is released regardless of whether or not an error occurs. © SAP AG JA100 10-7 7\SH6SHFLILF*HWWHU0HWKRGV !«G & . Export parameter interface ERRNLQJLQIR ... FLDATE ... ... BOOKID ... Ê Ê /1&2 5 !Ë 71,-Q/.8-;Q,~0/>8/ BOOKINGDATA ... ... ... ...... IXQFWLRQ FLDATE 20060713 BOOKID ... ... ... Ê Ê /12 5 1#Ë 71,-Q/.8-;Q,1 0/>8/ HHÌI KL M N K&OQPSR T UU ] Q^ y<zÍvx*&^6v&_QYZ^*\*Z­ Î@[^ yxXlX&\CY*`*§^>Ïm Ð ®xQxQ±YZQ` Y+Z XQx!v`Cy.^+]^+_QY*Z`F mf¢d*¥+h*jm .q date of flight: 2006-07-13 SAP AG 2004 A structure consists of individual components, all of which have their own data type. But Java uses different data types than ABAP, so mapping between the data types must take place. The component FLDATE from the export structure BOOKINGDATA of the function module BAPI_SBOOK_CREATEFROMDATA, for example, has the ABAP data type G. The table below shows the different data types in the two programming languages, as well as the mapping between them. The table shows that ABAP type d is mapped to the Java type java.util.Date. The class JCO.Structure provides type-specific getter methods for accessing the individual components of an ABAP structure via the respective Java representatives. For example, the method getString( ) returns the value of a component as a Java string. If this method is called for the component FLDATE, it converts the date into a string and returns it in the form YYYY-MM-DD. © SAP AG JA100 10-8 7\SH6SHFLILF*HWWHU0HWKRGV -&R -&R 7\SHVSHFLILFJHWPHWKRGV 7KH6$3-DYD&RQQHFWRU DXWRPDWLFDOO\FRQYHUWVWKHILHOG FRQWHQWVWRWKHUHTXLUHGGDWDW\SH HHJI K&LQM N KOCP RT.U&U 6WUXFWXUH getInt(String): int getInt(int): int getString(String): String getString(int): String getBigDecimal(String): BigDecimal getBigDecimal(int): BigDecimal getDate(String): Date getDate(int): Date getTime(String):Date getTime(int):Date getDouble(String): double getDouble(int): double getByteArray(String): byte[ ] getByteArray(int): byte[ ] ... ÑQÒÓÔÕ>Ö ÑQÒÓÔÕ>Ö ×ØÙ>Ø«Ú$Û>ÖÑÜÌÚÃÝ>ØÖ ÞJß ×ØÙ>Ø«Ú<Ö Þà6Ö«ÚpáÑQÒÓ#ÜÞÝ6Ø>ÖÞ6â&ÔÕÒ>Ø1Ö~ß ÝØÖ&ÞäãÜå.Ø.Ö&Þçæ èÔÔ&é6Ñêë.Ñê.ã.ÔìÚ$ëÞ6ÖÝØ1ÖÞ:í îQâ&ïÝð!ñò­î óFß áÑQÒÓ1ÜÞÝ1Ø6ÖÞ6âÔ6ÕQÒØÖôÒ6õÝØ1Ö Þ6âÔ6ÕÒØ.Ööæ êÞ÷ áÑÒÓ#ÜÞÝ6Ø>Ö ÞâÔÕÒ1Ø>ÖJí î ååøÚùùÚnõõõ&õ­î ó?ß áQõ!ú.Ö Þ&ÒSÚfÔ&Û6Ö«ÚÓ#ÕÑê6ÖÜ&êûí üCåØÖÞýÔãýãÜÑëþ6Ö«ÿôî Ò>õÝ.Ø1Ö Þ6âÔ6ÕQÒØ6Ö Ú$ã&Ô6ÕQÒØ6ÖøíãÜåØ1Ö Þ#óó­ß date of flight: 13.07.2006 SAP AG 2004 Whenever a type-specific getter method is called, the SAP Java Connector always tries to convert the contents of a component to the required type. This, naturally, can fail – for instance if the method getDate( ) is called for a string component that has the value “HUGO.” In this case an exception is triggered. The example lists all type-specific getter methods of the class JCO.Structure. There is also the method getValue( ), which can be used to access component contents generically. This method returns an instance of the class REMHFW. The example code uses the method getDate( ) to format the output of the flight date. At the same time, the contents of the component FLDATE are requested as a 'DWH object via getDate(). The date, represented as a 'DWH object, can then be formatted via an instance of the class SimpleDateFormat. © SAP AG JA100 10-9 0DSSLQJ%HWZHHQ-DYDDQG$%$3'DWD7\SHV 0DSSLQJRIWKH6$3-DYD&RQQHFWRU JCo type code Java data type ABAP data type 87 5 9( +:9; .C-*D0 87 5 9( +:9; .C-*/ 87 5 9( +:9; .C-* 87 5 9( +:9; 87 5 9( +:9; -#B!" && 0 = 1 1 & 45) 56&# 87 5 9( +:9; & : 45) 56&# 87 5 9( +:9; .)" , 87 5 9( +:9; ,A 7Ì & 123 87 5 9( +:9; 1(@ : 87 5 9( +:9; =!.6-?> : 87 5 9( +:9;1< =8.6-?> . . 1 . . / 87 5 9( +:9; & 123 Description -! 1 QG, &# ')(*(+(*(!""&!& % û !#"$" 1% & . & . SAP AG 2004 In ABAP, there are two different data types for handling date and time information. Type T is used for times, and type D is used for dates. In Java, on the other hand, time and date can both be stored using the same data type, the class 'DWH. In other words, an object of the class 'DWH can accept both calendar dates and times of day. As you can see in the mapping overview, data objects of both type T and type D are represented in Java via objects of the 'DWH class. When displayed, the unused part of the 'DWH object is simply left at its initial value. It is the programmer’s job to determine whether a'DWH object represents an ABAP time or an ABAP date and to handle it accordingly. Whether data type D or data type T is behind a 'DWH object can be viewed in the SAP system during compilation. It is also possible to obtain this information at runtime via an object of the class JCO.MetaData. We will now demonstrate how to do this by way of a short example. The function module BAPI_SBOOK_CREATEFROMDATA has an export structure BOOKINDATA, which is represented in the Java program via the object bookinginfo (see above). You generate a metadata object for this object, that is, an instance of the class JCO.MetaData. Using the method getType( ) you can then query the data type of individual components with this metadata object. Ideally, this is done using public type code constants from the class JCO: JCO.MetaData md = new JCO.MetaData(bookinginfo); if (md.getType("FLDATE") == JCO.TYPE_DATE) System.out.println("ABAP Typ d"); if (md.getType("FLDATE") == JCO.TYPE_TIME) System.out.println("ABAP Typ t"); © SAP AG JA100 10-10 0DSSLQJ%HWZHHQ-DYDDQG$%$3'DWD7\SHV 0DSSLQJRIWKH6$3(QWHUSULVH&RQQHFWRU ABAP data type Java data type Description , 4 15 0 E. 56& .¸ . -!û +&# , . E. 1 . G . û#!"" , / 123 23 1 . , > &C&G, 5 û &# H(*(I(?(@"$"&!& % 4 15 1 . G !% & E+F 1 , & E+F 1 SAP AG 2004 The SAP Enterprise Connector generates more typical setter and getter methods for accessing the interface parameters. In other words, fields are accessed by their names (for example, getFldate( )) and not, as in jobs with the Java Native Interface, by type-specific get methods (for example, getString(“FLDATE“)). The mapping between ABAP and Java data types used by the SAP Enterprise Connector can be seen in the example above. If, for example, a function module has an interface parameter FLDATE of the ABAP type D, the SAP Enterprise Connector generates a method getFldate( ) that returns the value of the parameter as an instance of the class java.sql.Date. © SAP AG JA100 10-11 ,QWHUIDFH3DUDPHWHU7DEOHV Connections from Frankfurt to New York: FROMCOUNTRYKEY DE Carrier LH LH UA UA FROMCITY FRANKFURT TOCOUNTRYKEY US TOCITY NEW YORK ... ... flighttime 444 455 495 495 CONNECTIONNUMBER 0400 FLIGHTDATA ... FLTIME DATEOFFLIGHT ... 20060728 444444 . ;. A. >F* ; > : +A,. FLIGHTLIST CARRID CONNID FLDATE 20060728 LH 0400 0402 20060517 LH 3517 20060613 UA UA 3517 20060730 Date 28.07.2006 17.05.2006 13.06.2006 30.07.2006 AIRLINECARRIER LH % Connid 0400 0402 3517 3517 ... ... ... ... ... ... ... ... A « . ; ,A,. >$ ; > : & : .)A SAP AG 2004 Here you want to call the function module BAPI_SFLIGHT_GETLIST from within a Java program and, at the same time, pass a departure and arrival city. The function module will return a table with all flights between the two cities. For each flight, that is, for each line in the table that was returned, you would then like to find out the flight time. To do so, use the function module BAPI_SFLIGHT_GETDETAIL. Pass the key of a flight – consisting of airline, connection number, and flight date – to the function module. You will receive a structure with detailed information on this flight. Above all, this structure also returns the desired flight time. © SAP AG JA100 10-12 ,QWHUIDFH3DUDPHWHU7DEOHV -&R HHÌI KLM N KO P R TUU JEKL Ú$ñ.ØQè?ÜÞäãÜÑë.þ6Ö>úôæ ãÛ+ ê MON!ë.Þ>ÖÜÑ1úÖìÚ ëÞ1Ö&ñ.Øè#Ü+ Þ PØ6Õ&Ø Ò!Þ6Ö&ÞÕïÑ1úÖÌífóFÚ ëÞ!ÖñØQè#Ü&Þ í î+â, ï QRS>ñ ï Q.áñFî óÍß -&R 7DEOH getNumRows(): int setRow(int): void getRow(): int appendRow(): void appendRow(int): void deleteAllRows(): void deleteRow(): void deleteRow(int): void insertRow(int): void setValue(String, String): void getString(String): String ... . ... ... IXQFBJHWOLVW . ; ,A. >D ; > : A. CARRID CONNID FLDATE 0400 20060728 LH 0402 LH 20060517 3517 20060613 UA UA 3517 20060730 IOLJKWV ... ... ... ... ... SAP AG 2004 In the Java program, tables are represented by objects of the class JCO.Table. To receive the Java representative of the table parameter FLIGHTLIST of your function module BAPI_SFLIGHT_GETLIST, you first have to gain access to the table parameter list via the function object (getTableParameterList( )). Then the concrete table is returned from this list via getTable( ). The class JCO.Table has all the methods that the class JCO.Structure has. Moreover, it has methods for navigating within a table and for manipulating a table. Further information on the methods mentioned here can be found in the SAP Java Connector API documentation. © SAP AG JA100 10-13 ,QWHUIDFH3DUDPHWHU7DEOHV ã&ÔÕ í Ñê!Ö Ñ æjiÍß Ñlk ã6Ü&Ñë&þÖú ÚnëÞÖOm1ÛÒ+n.Ô÷!ú«ípó#ß Ñópo ãÜÑë&þ6Ö>ú­Ú<ú Þ!Öqn>Ô÷ íwÑ6óÍß áÖÕÑê&ëpMØ.ÕÕÑåçæýã6Ü&Ñë&þÖú ÚnëÞÖ&áÖÕÑêëí î K ðnn*QCÝ î ó#ß áÖÕÑê&p ë MÔêê.Ñåçæýã6Ü&Ñë&þÖú ÚnëÞÖ&áÖÕÑêëí î KL mm#QCÝ î ó#ß áÖÕÑê&ë ã.Ü&å6ØÖ&Þçæýã6Ü&Ñë&þÖú ÚnëÞÖ&áÖÕÑêëí îâ&ïÝð?ñòÍî ó#ß ãÛêIMrN>ë6Þ6ÖåÞ!ÖØ6ÑÜÌÚnëÞÖQQÒÓÔÕ>ÖP&Ø>ÕØÒ6Þ!Ö Þ>ÕïÑ!úÖSíóÍÚ úÞqÖ s1ØÜÛ6Þ í M&Ø6ÕÕÑ.u å t îp? ð QEn. ï Qqm.ò K ð nn*QQ ò n î ó~ß AIRLINECARRIER ãÛêIMrN>ë6Þ6ÖåÞ!ÖØ6ÑÜÌÚnëÞÖQQÒÓÔÕ>ÖP&Ø>ÕØÒ6Þ!Ö Þ>ÕïÑ!úÖSíóÍÚ úÞqÖ s1ØÜÛ6Þ í M&Ô.êê.Ñ.u å t î K9L mmò K + ñ Q L mmIv ù w69 ò nÍî ó~ß CONNECTIONNUMBER ãÛêIMrN>ë6Þ6ÖåÞ!ÖØ6ÑÜÌÚnëÞÖQQÒÓÔÕ>ÖP&Ø>ÕØÒ6Þ!Ö Þ>ÕïÑ!úÖSíóÍÚ úÞqÖ s1ØÜÛ6Þ ínãÜåØÖu Þ t î+Ýð?ñò L â&â ï Q9R9S>ñî óÍß DATEOFFLIGHT Ò K Ô.êê&Þ+M.ÖÑÔ.êìÚ@ÞàÞMÛ#ÖÞûíwãÛêIMrN1ë6ÞÖ&åÞ!ÖØ6ÑÜóÍß JK9L áõ!ú.Ö ÞÒûÚÔÛ1Ö«ÚÓ#ÕÑê6ÖÜ.êSíM&Ø6ÕÕÑåx îýî yMÔêê.Ñåz ãÜ&Ñ.ë&þ!ÖåÞ6ÖØÑÜú­Úfë&Þ!ÖáÖÕÑêë í îQâï6ñ,QCù>ò?î ó&ó~ß ... FLTIME ... Ê /12 56;Q"*2 4D8< 4-80- 8/2E" Úfá&Ö.ÕI Û MÖÛÕÞäãÜÑ.ëþÖ åÞ6ÖØÑÜ!úôæ ãÛê+MrNëÞ!Ö åÞ6ÖØÑÜJÚÃëÞ6Öòà&Ó>ÔÕ1ÖEP.ØÕ.ØÒ!Þ>ÖÞ1Õï6Ñú.ÖÌífó­Ú ï QcR9S1ñÝð!ñ ð î óFß ë.Þ>ÖáÖÕ+ Û M.ÖÛ!ÕÞûí îQâ îýî ãÜ&å6ØÖ&Þ{ Tad)b ZIe+\^],[f\g`Eb6d h T UVIWYXZD[\^],[_\a`cb)d îýî | SAP AG 2004 The table parameter FLIGHTLIST of the function module BAPI_SFLIGHT_GETLIST returns all flights between two specified cities. To calculate the flight time for each flight, call the function module BAPI_SFLIGHT_GETDETAIL for each line of the table. To do so, program a IRU loop via the Java representative of the table parameter FLIGHTS. The method getNumRows( ) then returns how many lines the table contains. Using the method setRow( ), set the line pointer to the individual lines. The first line has the index 0 and the last line the index (getNumRows( ) – 1). The fields in a table line are addressed in the same manner as the components of a structure. A structure, after all, is nothing but a special type of table with only one line. The function module BAPI_SFLIGHT_GETDETAIL expects the key of a flight as an entry parameter consisting of airline, connection number, and flight date. These elementary parameters have the names AIRLINECARRIER, CONNECTIONNUMBER, and DATEOFFLIGHT. The values for these parameters are passed using the method setValue(), which is called directly along with the import parameter list of the function. After calling the function module BAPI_SFLIGHT_GETDETAIL, you evaluate the export parameter FLIGHTDATA of this function module. From this structure, take the value of the component FLTIME and output it on the console together with the flight key. © SAP AG JA100 10-14 2SWLPL]LQJ3HUIRUPDQFH -&R 2SWLPL]LQJSHUIRUPDQFH 8QQHFHVVDU\RSWLRQDOWDEOH SDUDPHWHUVFDQEHGHDFWLYDWHG ãÛêIM.ÖÑ&Ô.ê«ÚëÞ6Öñ&Øè1ÜÞ,PØÕ&ØÒ6Þ!Ö Þ>Õï6Ñ.ú&ÖSíóÍÚ úÞÖ+ ð M>Ö&Ñ&Ù.Þ í ãØ>Ü.úÞ t î Qñ*D ð wFî óFß -&R ,7$% 3DUDPHWHU/LVW ... ... ... ... setActive(boolean, String): void setActive(boolean, int): void ... >C6 & & ... ... ... ... Ê ... ... ... ... /!2 8Q/ Ê ... ... ... ... "Q- 5 SAP AG 2004 Many BAPIs have a large number of interface parameters, some of which may not always be needed for a concrete application. To improve performance, it is therefore a good idea to only exchange those values that are needed between the Java program and the SAP system. There is no way of preventing certain parameter values from being returned by a function module. It is possible, however, to set it up so that parameter values from the Java container are not passed to the Java layer. This is only possible for optional table parameters. To do this, simply declare the optional table parameter as inactive, as seen in the example. The default of the Boolean parameter of the method setActive( ) is true. This means that table contents are sent and received. If the parameter is set to IDOVH, the table contents are not sent to the remote system, that is, they are not accepted by it. © SAP AG JA100 10-15 ,QWHUQDODQG([WHUQDO'DWD)RUPDWV ! & External data format (in/output format) Flight time 8:15 Automatic conversion in SAP system when input or output via conversion exits Internal data format & 495 do_fltime %$3,V UHTXLUHRU RIWHQUHWXUQWKH LQWHUQDOGDWDIRUPDW '% spfli ... fltime ... ... ... ... 495 ... ... ... ... ... SAP AG 2004 ,QWHUQDOGDWDIRUPDW means the data is the form of an ABAP program and that it is persistently stored in that form. ([WHUQDOGDWDIRUPDW, by contrast, is used for input and output of data on the front end. As the terms themselves suggest, the internal and external data formats do not have to be the same. In the example we see that the flight time is expressed in minutes in the internal format. On the front end, however, it is expressed in the form h:mm. Conversion between these two forms is executed automatically in the SAP system via FRQYHUVLRQH[LWV. Conversion exits are function modules that are stored on the domain level. The conversion must always be executed in both directions. If, for instance, a flight time is to be displayed on the front end, the internal minute display must be converted to the hours:minute display via the conversion exit. If, on the other hand, the user enters a flight time on the front end, he uses the hours:minute display; this is then converted to minute display for internal processing via the conversion exit. BAPIs generally use the internal format. If a user wants to offer the external data format for the user interface in his client application, he can perform the necessary conversions using conversion BAPIs. © SAP AG JA100 10-16 'DWD)RUPDW&RQYHUVLRQ ... DATA OBJTYPE OBJNAME METHOD PARAMETER FIELD ... INT_FORMAT EXT_FORMAT ... .; 87 - É}: = . 7 - ; .6-*,/ :1< D0 External data format (flight time in h:min) Internal data format ~ u* 8+}I8 I *D (flight time in min) ... DATA OBJTYPE OBJNAME METHOD PARAMETER FIELD ... INT_FORMAT EXT_FORMAT ... SAP AG 2004 To convert data from the internal to the external format, use the function module BAPI_CONVERSION_INT2EXT1. To convert data in the other direction, use the function module BAPI_CONVERSION_EXT2INT1. The interface for both of these function modules is structured identically. Both have only two table parameters, DATA and RETURN, as interface parameters. Now let’s take a closer look at the function module BAPI_CONVERSION_INT2EXT1 so that we can use it to convert a flight time from the internal to the external format. For each value to be converted, a line in the interface table DATA is passed. To access the domain conversion in the SAP system, however, the function module needs not only the value to be converted, but also the information specifying which conversion exit is to be used. Thus the interface parameter of the BAPI that uses the value to be converted is also entered. To identify this BAPI, it is necessary to specify the business object type for which the BAPI in question represents a method. This can be done via the fields OBJTYPE or OBJNAME. The object type is the internal, technical key of a business object in the Business Object Repository, while the object name is more of a description represented by a name in English (for example, SalesOrder). Both designations can be searched in the transaction EDSL. The name of the BAPI is given in the METHOD field and the name of the interface parameter in the PARAMETER field. The FIELD field incorporates the name of a field within a structured parameter. Pass the value to be converted via the field INT_FORMAT. After calling the function module, you will receive the converted value in the field EXT_FORMAT. © SAP AG JA100 10-17 'DWD )RUPDW&RQYHUVLRQ u AIRLINECARRIER LH CONNECTIONNUMBER 0400 FLIGHTDATA ... FLTIME DATEOFFLIGHT ... ... 20060728 444444 q9E9 ... ... ... ... BAPI_CONVERSION_ INT2EXT1 returns for EXT_FORMAT the value 7:24 % ~+u* 8 1 1D# u A DATA ... INT_FORMAT EXT_FORMAT METHOD PARAMETER FIELD OBJTYPE OBJNAME FlightConnection GetDetail FLIGHTDATA FLTIME 444 OBJNAME and METHOD can be taken from the transaction 9, ... ~+u* !+u8 DI9DD SAP AG 2004 The function module BAPI_SFLIGHT_GETDETAIL returns detailed information about a flight via the export structure FLIGHTDATA. The flight time in the internal format is found in the component FLTIME. To convert it into the external format, we call the function module BAPI_CONVERSION_INT2EXT1 and fill the table parameters as described. As we only want to convert one value, we only need to fill one line in the table. The function module BAPI_SFLIGHT_GETDETAIL represents the implementation of the BAPI FlightConnection.GetDetail, which you can take from the transaction EDSL. Consequently, the fields OBJNAME and METHOD should be filled with FlightConnection and GetDetail, respectively. As you want to convert the component FLTIME from the parameter FLIGHTDATA of this BAPI, pass exactly these values for PARAMETER and FIELD. The last step is to fill the field INT_FORMAT with the flight time in the internal format and call the conversion function module. The field EXT_FORMAT is then automatically filled with the value in the external format. © SAP AG JA100 10-18 'DWD)RUPDW&RQYHUVLRQ WE³V´YX]`\C` Tad6b Z+e+\^],[f\g`cb)d h ... ... FLTIME ... OBJNAME METHOD PARAMETER FIELD INT_FORMAT EXT_FORMAT TUVWXZD[E\^],[f\g`Eb6d Ê TU1V+WXb6V+\a°[²±,\ />&2 Q5>;C"*2 4#D8 4#-806-8/62E" E¡+¢E£ ¤c¥,¦*§E¨+©9ª«£ ¦*§q¤ £6§9¬f­q©_®,¬¯ H&HJI K LQM N K&OCP R T UU W r s*u*cFvwC[ ®&\Cy Qx*Z_µ<e&[ ^*[ k X*QZ feY*Z^+rQy*&^6v`y^+[ ®&\Cy a*[Q_Q[ zy&^<yQ_CdYQ^w!v`y^+[ ®&\Cy­ m@¥<hph1m q Qx*Zfµ e&[ ^*[vn[ CyZCQQx*¤Ínq W WQW W+r W* W Qx*Zfµ e&[ ^*[v@<y^·¶[Q\+Qy­ m<¢ \CY*`*§^<uQxCZZQy ^*Y*xCZ.m m@cQ£spg*hijm q internal format: 444 Qx*fZ µ e&[ ^*[v@<y·^ ¶[Q\+Qy­ Ym ¸y^ ¥Qy&^+[QYQ\.m mnijq ¹+cQ¥>m q external format: 7:24 Qx*fZ µ e&[ ^*[v@<y·^ ¶[Q\+Qy­ m<¢QdY¡ ¸f¹*¥ h+h1m mpafhphij*jm .q Qx*fZ µ e&[ ^*[v@<y·^ ¶[Q\+Qy­ m<¢QdQ¡i&jm mp¢&¡pjQd*¥.m q Qx*fZ µ e&[ ^*[v@<y·^ ¶[Q\+Qy­X\Y+`C§^+Qy^+[YQ\6v`Cy^C]^+_Y*ZC`~ mf¢Cd¡fi&jm . m*¡$g<e¢CcQ<i h&m .q zuQxQZQZCy^+YCx Z#vyC yQ*^+y­wX*QZ@eY*Z^+r yC^Q.q ]<&^<y z~vxC&^v¬_YCZ^*\+Z­ m+YCZ^<yQ_QZ[Q\bXQx_pz&[ ^>Ï©m l Ð X \QY+`C§&^< y&^+[QYQ\6v`Qy^] ^*_QY*Z`­ m ¢CdQ¡$ijm Cq ]<&^<y z~vxC&^v¬_YCZ^*\+Z­ m yQ^<yQ_QZ[Q\bXQx_pz&[ ^>Ï©m l Ð xCZrµ e[&^*[v`Qy&^+] ^+_QYZQ`~ mfjqº@e.¢*cQ<iChm Cq SAP AG 2004 The program code shows the syntax of a format conversion. After you have instantiated the Java representative for the function module BAPI_CONVERSION_INT2EXT1, you use it to get the representative of the table parameter DATA. Using the method appendRow( ), generate one line in the JCO.Table object. If there are already entries in this object, the new line is added to the end of the table. The line pointer is automatically set to the just-added line, so you can immediately begin to fill the line. The position of the line pointer is retained when the function module is called. In other words, even after calling the BAPI_CONVERSION_INT2EXT1 in the SAP system, the line pointer remains on the added table line. You can therefore access the contents of the field EXT_FORMAT without having to reposition the line pointer. © SAP AG JA100 10-19 ([FHSWLRQ+DQGOLQJ 5XQWLPH([FHSWLRQ -&R UHFRJQL]HV WKUHHGLIIHUHQW H[FHSWLRQFODVVHV -&2([FHSWLRQ »@Ë ¥¦¤©1ª,ª¦*ªq¤9ÌfÍ,§9¥¬E£ ¦?§q¤§¦+¬Î¤1ÌO¦?Í,§Ï ÆÎÇ6ÈY¾ »@Ë ¥¦¤©1ª,ª¦*ªq¤9ÐO¦ ¿ ¦?§f¤9Ìr¡,£6Ð_ͪ,© ÆÎÇ Èr¾ »@Ë ¥¦¤©1ª,ª¦*ªq¤q«Ñ1«¬9©fÒ+¤Ì²¡£ ÐfÍ,ª,© ÆÎÇ Èr¾ ÓÓÓ »}¼r½O¾H¿DÀgÁEÂfÃfÄ6ÅÆOÇ)Ⱦ »}¼r½O¾aÉ9½YÊOÄ Å Æ « ¾aÀ^Ç Èr¼ »@¾HÁ « ¾aÀÇ Èr¼_Ä ÅÆ « ¾aÀÇ Èr¼ -&2$EDS([FHSWLRQ -&2&RQYHUVLRQ([FHSWLRQ SAP AG 2004 The exceptions thrown by the JCo are subclasses of java.lang.RuntimeException. In other words, these exceptions do not need to be handled via WU\FDWFK or declared in the method signature. JCo recognizes only three different exception classes: JCO.Exception, JCO.AbapException, and JCO.ConversionException. The latter two are subclasses of JCO.Exception and can be handled separately if necessary. The getGroup( ) method defined in JCO.Exception makes it possible to distinguish between different error types. These error groups, such as JCO_ERROR_LOGON_FAILURE, are defined as public constants in the class JCO.Exception and can be referenced in the API documentation for JCo. The exception JCO.ConversionException is triggered when a set or get method is called that performs a conversion and the conversion fails. This can happen with the method getDate(), for example, if it tries to convert field contents in the Java type 'DWH. The exception JCO.AbapException occurs when a called remote-capable function module triggers an ABAP exception. For example, the function module DDIF_FIELDINFO_GET throws the ABAP exception NOT_FOUND if the structure or table passed when it is called is not found in the ABAP Dictionary. © SAP AG JA100 10-20 ([FHSWLRQ+DQGOLQJ Ô JKL ÚâÛ6êM>ÖÑ.Ôê ÖÕõ o ãÛêM>Ö&ÑÔê æ Öþ1Ñ6ú ÚMÕÞ>Ø.ÖÞâ&Û6êM>ÖÑÔêí î ÝÝQ&ârNFâ,Qòï&ÝDQOmâ L N+Rò6ñî ó?ß Õ Ö ãÛ6êM>ÖÑ.ÔêøÚÃë6ÞÖ1QQÒÓ!Ô.Õ>ÖEPØÕ&ØÒ>Þ!Ö Þ>Õï>Ñ.úÖøí$óÍÚpúÞÖqs>Ø.Ü&Û.Þûí îpù&ðDnðÌî t × î*ñ ð,w1mðù>òFî ó?ß Ò K Ô&êêÞIMÖÑÔê«ÚnÞàÞMÛÖÞ íãÛ6ê,M>ÖÑ.Ôê?ó#ß Ø Ù | MØÖMþ Ñã Û í JKL Úªð>è6ØÓ1ò.àM&Þ&Ó!Ö.ÑÔ&ê Þà1óÚo íÞàøÚëÞÖ9ÜÞõ í$ó~ÚÞ,ÝÛ1ØÜú,Q ëêÔ6ÕÞ K Ø>úÞí î·m L ñcN1â L v9m>Ý­î ó&ójo áQõ?úÖ&ÞÒûÚnÔÛÖÍÚÓ!ÕÑêÖÜêûí î+Ý6Ñ,MÖ.ÑÔêØ.Õ&õ Þ Þ.Ü1úÞ à | ãÔÛ.êåøÚCî ó#ß o áQõ?úÖ&ÞÒûÚnÔÛÖÍÚÓ!ÕÑêÖÜêûíÞàìÚ@ë&ÞÖ<ù1Þ!úú&Ø&ëÞSípó&óFß Ô i Ô9Ô | MØÖMþ ÔqÕ | í JKL Úò>à1MÞ&Ó#ÖÑÔ.êýÞ&à1óáo ßßâS6Ø&êåÜÞ ÔEÖ MØÖMþ Ô × | ÖQþÞ Þ.à,MÞÓ­ÖÑ&Ô.ê íªò6à,MÞÓ­ÖÑ&Ô.êýÞà#ójo ßßâS6Ø&êåÜÞ Ô Ø ÔÙ úÖ.Õ ÛM6Ö Û1ÕÞDßÖØQè#Ü&ÞýêÔ1Ö ÖQþÞ Þ.à,MÞÓ­ÖÑ&Ô.ê | SAP AG 2004 In the example above, the remote-capable function module DDIF_FIELDINFO_GET is called. This function module finds meta information on a passed structure or table in the ABAP Dictionary. If the structure or table is not found, the function module triggers the ABAP exception NOT_FOUND. The first FDWFK block handles the exception triggered by the function module. The name of the ABAP exception is queried using the getKey( ) method. If the exception in question is NOT_FOUND, a self-defined text is output. Otherwise an appropriate output text is obtained via the method getMessage( ) and is then displayed. The second FDWFK block catches all other exceptions that are related to the JCo. These include all conversion errors (that is, exceptions of the type JCO.ConversionException), as there is no separate FDWFK block for them. The third FDWFK block handles all other exceptions that can occur in the code in the WU\ block. © SAP AG JA100 10-21 'HEXJJLQJDQG7UDFLQJ X ëìaë íYîï ðgñCòCòaï ó -&R è é²ê ãaä åæ,æ,ææ,æ æ1æ,ææ1æ,ç ãå - - -&R ôôõ ö÷qø ù ö9úfûücý,þ þ &OLHQW Ò K Ô.êê&ÞIM.ÖÑ&Ô.êìÚ+ú Þ1ÖñÕ.Ø1MÞí Ö&ÕÛÞ ó~ß Ô Õ áõ!ú.ÖÞÒ:ÚÔÛ>Ö«ÚÓ#ÕÑê6ÖÜê í îCñ.ÕØMÞìÿôî Ò K Ô.êê Þ M>Ö&ÑÔ&êìÚ@ëÞ!ÖñÕØMÞ ífóó~ß Ö × getTrace(): boolean setTrace(boolean): void getAbapDebug(): boolean setAbapDebug(boolean): void ... Ø Ù Ò K Ô.êê&ÞIM.ÖÑ&Ô.êìÚ+ú Þ1Ö+ðèØÓ>ÝÞè6Û6ëSí ÖÕÛ6Þ ó­ß à áõ!ú.ÖÞÒ:ÚÔÛ>Ö«ÚÓ#ÕÑê6ÖÜê í î@ð+wð?P Ý>Þ è1Û.ëJÿ î Ò K Ô.êê Þ M>Ö&ÑÔ&êìÚ@ëÞ!Ö+ð6è1ØÓÝ.Þ&èÛ6ëí@óó~ß Û Þ Ô i Ô Ô Ò K Ô.êê&ÞIM.ÖÑ&Ô.êìÚMÔêêÞIM.ÖSí$ó­ß SAP AG 2004 If an RFC error occurs during communication with the SAP system, a file named dev_trc.trc is automatically created in the error log. The directory in which this file is created can be set using the environment variable RFC_TRACE_DIR. An RFC trace can also be executed by setting the environment variable RFC_TRACE to . If this environment variable is not set or is set to the value , the trace can be deactivated via the instance method setTrace(boolean) from the class JCO.Client. The trace generates a file named rfcnnnnn_nnnnn.trc; the directory for the file is set using the environment variable RFC_TRACE_DIR. If the trace is activated by calling setTrace(true) in a direct connection, this call should take place before calling the connect() method for the JCO.Client object. Otherwise, the connection to the SAP system will be closed and then reopened. This can result in a loss of data. It is also possible to debug the ABAP code. The ABAP Debugger can be activated using the method setAbapDebug(boolean) from the class JCO.Client. Here, too, if the trace is activated by calling setAbapDebug(true) in a direct connection, this call should take place before calling the connect() method for the JCO.Client object. Otherwise, the connection to the SAP system will be closed and then reopened. This can result in a loss of data. If ABAP debugging is active, the SAP GUI is automatically started and the processed ABAP code is displayed in the debugger. © SAP AG JA100 10-22 'HEXJJLQJDQG7UDFLQJ 'XPSDQLQWHUIDFH SDUDPHWHULQWRDQ KWPOILOH -&25HFRUG -&2)XQFWLRQ ÿ À^Ç ¾)½ ¬qÒuÐ Ä « ¾aÀ^Ç Èf¼_Å ÆcÁEÇ ÿ À^Ç ¾)½ ¬cÒuÐ Ä « ¾^À^Ç Èf¼_Å ÆEÁEÇ -&23DUDPHWHU/LVW -&27DEOH -&26WUXFWXUH ÿ À^Ç ¾)½ ¬qÒuÐ Ä « ¾^À^Ç Èf¼_Å ÆcÁEÇ ÿ ÀÇ ¾H½ ¬EÒ!Ð Ä « ¾aÀÇ Èf¼rÅÆÁcÇ ÿ ÀÇ ¾)½ ¬cÒ!Ð Ä « ¾^À^Ç Èf¼rÅÆEÁcÇ ô ô õ ö÷qø ù ö9úfûü ýþþ JEKL Ú$ñ.ØQè?ÜÞ ãÜÑë.þ6Ö>úôæ ãÛêIMON?ë&Þ>ÖÜÑ1ú&Ö«Ú ëÞÖ.ñØ è#ÜI Þ P&Ø6ÕØ&ÒÞ!ÖÞ.Õ.ïÑ1úÖ íó~Ú ë6ÞÖ&ñ.Øè#ÜÞûí îâ& ï QER9S>ñ& ï Qá.ñî óFß ãÜÑë&þÖú«Ú÷6ÕÑ.Ö&ÞS>ñ*ù?ïøí K ÿ &â ï QcRSñ.á«Ú S6ñQù#ï#î ó#ß SAP AG 2004 The classes JCO.Record, JCO.ParameterList, JCO.Table, JCO.Structure, and JCO.Function all offer the method writeHTML(String), which makes it possible to write an html dump of the corresponding object into a file. The file name is passed at the time of the call to the interface of the method. This makes it possible to check the parameter values that are passed or received when a function module is called. The example refers to BAPI BAPI_SFLIGHT_GETLIST, which is called in the SAP system. When a call is made via the interface, a departure and an arrival city are passed to this BAPI. The BAPI then gets all flights available between the two cities and returns them via the table parameter FLIGHTLIST. To view the contents of this table after it is called, the method writeHTML() is called with the object of the type JCO.Table. It generates an html file that contains the flights that were returned. By default, only the first 100 lines of a table are transferred to the generated html file. If more lines are desired, this can be done controlled by Property jco.html.table_max_rows. To get, say, 1000 table lines in the generated file, the following code can be implemented before calling writeHTML(): JCO.setProperty(“ jco.html.table_max_rows”, 1000); © SAP AG JA100 10-23 6\QFKURQL]DWLRQLQ0XOWLWKUHDG$SSOLFDWLRQV 2QO\DFFHVVWRSRRODQGUHSRVLWRU\REMHFWVLV V\QFKURQL]HG ,QPXOWLWKUHDGDSSOLFDWLRQVDFFHVVWRRWKHU REMHFWVPXVWDOVREHV\QFKURQL]HGLIDSSOLFDEOH * 5 6 C E J !#"%$'&)( !#"%$,+!.--/01'2 3& 4 ( !"%$,+ /7%!$89 :;7'!$ 8 : < :=/> ?@AB: &B4 DD +++ F 1/$ !#"'$,+ G% 01H &&I4 F SAP AG 2004 For performance reasons in the SAP Java Connector, only access to objects of the classes JCO.Pool and JCO.Repository is synchronized. As such, it may be necessary to undertake further synchronization in a multithread application if objects (for example, of the class JCO.Table) are shared between different threads. It should also be noted that it is not possible to execute several competing RFC calls using the same direct connection. Moreover, objects in a thread of the class JCO.Client that are requested from a connection pool should not be used in any other thread. © SAP AG JA100 10-24 W5)&T5)&DQGWKH ,'RF &ODVV /LEUDU\ -&R VXSSRUWVW5)& DQGT5)& IRULQERXQG -DYDFDOOV $%$3 DQGRXWERXQGFRPPXQLFDWLRQ $%$3FDOOV -DYD <RXFDQGRZQORDGWKH,'RF &ODVV/LEUDU\DW KWWSVHUYLFHVDSFRPFRQQHFWRUV &UHDWHVHQGUHFHLYHDQGUHDG,'RFV IURPZLWKLQ -DYDDSSOLFDWLRQV SAP AG 2004 The IDoc Class Library can be downloaded through the SAP Service Marketplace. You can find further details in the supplied documentation. Beyond the synchronous RFC (sRFC) presented here, the SAP Java Connector also supports tRFC and qRFC. The basis of the presented sRFC is the synchronous communication method, that is, the affected systems, must both be addressable at the time of the call. The transactional RFC (tRFC), by contrast, is an asynchronous communication method that executes the function module called in the SAP system exactly one time. As a consequence, the SAP system does not have to be addressable when the Java program executes a tRFC. If a call is sent while the receiving system is not available, the call remains in the local queue. The Java program can continue to run without waiting to find out if the function module was successfully called or not. Using the tRFC is expedient in situations in which you want to ensure that the transactional sequence of calls is followed. To guarantee a sequence of several Logical Units of Work (LUWs) specified by the application, the tRFC can be serialized using queues. This type of communication is also supported by the SAP Java Connector. This RFC type is known as queued RFC (qRFC). qRFC is an extension of tRFC. A LUW (transaction) is only transferred when there is no transaction in front of it in the queue. Using the qRFC is expedient in situations in which you want to ensure that the processing of different transactions is done in a particular order. © SAP AG JA100 10-25 ,QWHUQDWLRQDOL]DWLRQ KLML N O LPQ (YHU\LQVWDQFHRIWKHFODVV /RFDOH LGHQWLILHVDJHRJUDSKLFDO UHJLRQLQFOXGLQJWKHODQJXDJH VSRNHQWKHUH 2EMHFW KLML.N O /RFDOH S å R ' 'U ã æ'V æ'VIW V,%X 'T T ã æ'V å S W,æãg'Y æ'V{W V 1ã |~ +} y Z'Z[Z \ ]'^`_ aBbdcBe`\`]B^ _ aBbIf)g ' \']'^`_ aBbdcBe`\`]B^ _ aBb tug 9S Wæãg 1ã |~~ D ! 1æ[z h bBi h bBi \%][^%_[a/bkj l#m[b,l n \%][^%_[a/bkj l#b[h,l n l.oBpql rqs l.vxw,l rqs SAP AG 2004 © SAP AG JA100 10-26 ,QWHUQDWLRQDOL]DWLRQ KLML N O 5HVRXUFH%XQGOH sichern R Vq ~ W,æ y %U ã æ%V æ G%X T 'S å S å %Y c S W,ãåc ~ Wæ y 'T T T T R V q ã æ'V[U ã æ'V_f Y ã æ V ­ 7KLVLQVWDQFHORDGVDOONH\ YDOXHSDLUV RIWKHILOH 0\%XQGOHBGHB'(SURSHUWLHV 3URSHUW\5HVRXUFH%XQGOH ~ , W æ y T By # ç ã S 1ãa c save=sichern send=senden add=hinzufügen ... bI%]/{'^ b/ [h'mIa/b{BhBmBa/bg b[']{ ^'b''[h%m{ab Z b[/''h[mBa'bkj lBeI%[h m[a%b2l n h'b/i \`]B^ _Ba/bj lm%bHl n l.o[pl r[r2s ¯ wexBb%c Z ]{ Z ' h[ a%hj `'h[m a b Z b[`w%B% h j l/_Ib2l r rHs JHW%XQGOH LQVWDQWLDWHVDQ REMHFWRIWKHFODVV 3URSHUW\5HVRXUFH%XQGOH SAP AG 2004 © SAP AG JA100 10-27 3DFNDJHMDYDLR K;LML#NO LPQ K;LML.N ¡¡¢£#¤ ¾aÀ ¢¥ ¾¦¦ ,QSXW6WUHDP ¡¡¢£#¤ ¾aÀ ¢¥ ¾¦¦ 2XWSXW6WUHDP 2EMHFW ¡¡¢£#¤ ¾aÀ ¢¥ ¾¦¦ 5HDGHU ¡¡¢£#¤ ¾aÀ ¢¥ ¾¦¦ :ULWHU SAP AG 2004 The package java.io deals with communication: reading and writing messages. Comprising more than 60 classes, this package is one of the largest in Java. However, most classes are derived from the four abstract basis classes: InputStream, OutputStream, Reader, and Writer. © SAP AG JA100 10-28 2XWSXWYLD%\WH6WUHDPV Basis class of the output stream Enables output of complete objects Provides a byte stream for output in a file Enables output of strings and simple types in text format : Class for selecting the output device : Class with filter function (filtering occurs by nesting output streams) SAP AG 2004 © SAP AG JA100 10-29 ,QSXWYLD%\WH6WUHDPV Basis class of the input stream Enables reading of complete objects from an InputStream Provides a byte stream for reading from a file : Class for selecting the output device : Class with filter function (filtering occurs by nesting input streams) SAP AG 2004 © SAP AG JA100 10-30 6HULDOL]DWLRQ ([DPSOHRIWKH6HULDOL]DEOH LQWHUIDFH c ] { ¨_/I_ Z /] Z.© s /ªa'[^^'a%_x xeB«[a%_x' ¡¡ £ Èξ)½qÀ§ ¢¥ ½¦ ¦ c a bcxb'hI[ wbI'B_Ba'{¬_%Ia b®­ %'B_`%b w%B% h b`¯`s %'B_`%b°`_/hª b'hIuBh` m'¯}s ,a''^ b ¯x³r°­ {eB«Ia/_x'±j²w`[h Serializable 0\&ODVV ´{[ Z 'b%¯xdgµ%b%¯ªs ´{[ Z B m%¯ g·¶'tHs ¸ ¸ 0RGLILHU WUDQVLHQW SAP AG 2004 Serialization means converting an object existing in the main memory of the application into a format that allows you to write/read the object to/from a file or transport it using a network connection. The reverse is naturally also possible, that is, reconstruction of an existing object in serialized form in the internal format of the Java machine that is being used. The classes ObjectInputStream and ObjectOutputStream are available for de/serialization. Serialization offers a simple way to durably store data. To serialize an object, its class must implement the interfacejava.io.Serializable. It is a marker interface that does not define any methods. Attributes that are not to be serialized can be assigned the modifierWUDQVLHQW. © SAP AG JA100 10-31 6HULDOL]DWLRQ([DPSOH 5HDGLQJDQGZULWLQJREMHFWV GHVHULDOL]DWLRQ #¹-/ º!»!ª+ +¼ 4 ¡¡ £ ȾC½fÀÚ§ ¢¥ ½ ¦¦ -/8"%$½$!/ A/ ¹/( Serializable -8"'$¾!¿» ¹/!;ÀÁ2ÂÃÄ!Á/&Å( Æ Ç$!ȹÇ$!/²É 1 Æ 'Ç$!/ª ʺ#8BË!Ì#¹% : &`4 ( = $Í8%-8/À /!#¹ÏÎËÉ 1 =$Í8 -8/À !#¹Ð :ǪÑÓÒÒÔ/[+': & 4 Í"Bº /#Í8%-/8%À!.¹¾ÕÉ 1 Í"`º#%#Í8%-8%À!.¹Î&I4 I+1 Í"Bº#'ª¹Ç$!&I4 +++ =$/> -8%À!¹ÖÎ²É 1 =$%> #- 8/À!#¹ :#Ç2ÑÓÒÒÔ/I+×# : &B4 Í "Bº />. -8'À! ¹¾²É 1 Í "Bº >##-8'À! ¹ØÎ&B4 ¹Ç$!/ÕÉ· Æ Ç%$!/&ËI+!Í "Bº xÓ& 4 F F 0\&ODVV cBe`«[a'_x% F ! ?G#-{ÌG/&Ù( À '#¹H+8/{+ -//$9 Gx+Á/ Æ /!Á && 4 F Î!$$# ( DD Ͻ$Ï! ¹ +++ F SAP AG 2004 © SAP AG JA100 10-32 2XWSXWYLD&KDUDFWHU6WUHDPV Basis class of all character-based outputs For output buffering For output in a file : Class for selecting the output device : Class with filter function (filtering occurs by nesting output streams) SAP AG 2004 © SAP AG JA100 10-33 ,QSXWYLD&KDUDFWHU6WUHDPV Basis class of all character-based inputs Enables the conversion of a byte stream into a character stream For input buffering and for reading complete lines For import from a file : Class for selecting the input device : Class with filter function (filtering occurs by nesting input streams) SAP AG 2004 © SAP AG JA100 10-34 :ULWLQJWRD)LOH #¹-/ º!»!ª+ +¼ 4 -/8"%$½$!/ A/ ¹/( -8"'$¾!¿» ¹/!;ÀÁ2ÂÃÄ!Á/&Å( =$#Û%½Î1ÜÉ 8$$ 4 Ý 8ÎÎÛ/ Þ"1¿É 8$$ 4 ( Î1¿É 1 = $ ÛB2 :Ç,ÑÓÒÒ#/[+#G/': &`4 "1¿É 1 Ý 8 ÎÎ/Û% Î1%&B4 Î F F F Þɾ3{4ß²à¾* C 4áââ/&Ö( " 1,+1 :#$ãª+á: âã%&B4 "1,+ 1@9 &`4 F ! >.Í?G - ½/&Ù( À# # ¹q+8/I+Ø-//$9 ,+Á/ Æ !Á9 &&B4 F Î!$$ ( ( "1,+Ó$Ó&B4 F ! >.Í?G - ½%&Ù( À % #¹H+Ó8%I+Ú-'$9Ø,+Á% Æ / !ÁÓ&&B4 F F SAP AG 2004 © SAP AG JA100 10-35 5HDGLQJ)URPD)LOH ¹-' º!»!ª+;+¼B4 -8" $Ì$! A¹%Ù( -8" $ã!½» ¹/!H ÀÁ9ÂÃÄ!Á%&Ï( =$0!½Î¿É 8$$ 4 Ý 8ÎÎ0!Ä"%ÞÉ 8$$ 4 ÀÁÜ${4 ( ÎÄÉ 1 = $0! :Ç,ÑÓÒÒ /I+.G'%: & 4 "'ÄÉ 1 Ý 8 ÎÎ/0! Î/&`4 $ÞÉÞ"/ª+Ó!@Ó&B4 1$ F ! F F F $äÉ 8$$ &Ö( À' #¹q+ 8%{+Ú-%$$%&I4 $ÞÉÞ"/ª+Ó!@Ó&B4 Ø?G -IÌ%&Ö( À ' #¹q+ 8%{+Ú-%$Ø,+Á/ Æ / !Á;&&`4 F Î!$$# ( ( "'ª+$/ Ó&`4 F ! Ó>#Í?G#-B½%&Ù( À' #¹q+ 8%{+Ú-%$Ø,+Á/ Æ / !Á;&&`4 F F SAP AG 2004 © SAP AG JA100 10-36 7RNHQ $WRNHQLVDGDWDHOHPHQWWKDWLVVHSDUDWHG E\RQHRUPRUHGHOLPLWHUV LQWKLVFDVH³_´ 0HLHU_0DQXHOD_I__ å'æ#ç ç è×éê ë.éì í îê ïxê ðñò ðÓñò óôñ;ñ×ê å/èì è×éê åø þ õ×èç ø.ê ê ðó;ò ðó ò óô ê å'õ×öí èéê ÷øéç ê ï`ê ð;ù;ò ð×ú;ò ó ôúÓú.ê ûü×ý.þ èì ÿ#è×éê û õ;ö.ì ê ê ó ð;ò óù;ò ó ô ×ê SAP AG 2004 © SAP AG JA100 10-37 MDYDXWLO6WULQJ7RNHQL]HU KÓLML#NO L PQ KLML.N Ú O 2EMHFW 6WULQJ7RNHQL]HU 8VLQJWKHFODVV6WULQJ7RNHQL]HUWRNHQVFDQEHH[WUDFWHG IURPD6WULQJ z <RXFDQSDVVDGHOLPLWHUDVD6WULQJWRWKHFRQVWUXFWRU z 7KHPHWKRGKDV0RUH7RNHQV LQGLFDWHVZKHWKHUWKHUHDUHDQ\ WRNHQVOHIWWREHUHDG z 7KHPHWKRGQH[W7RNHQ UHWXUQVWKHQH[WWRNHQ SAP AG 2004 © SAP AG JA100 10-38 8VLQJ6WULQJ7RNHQL]HU c ]'I ¨_/I_ Z [ 'a Z w`/%Bh ] 'b`hBB¬%b }s 2a%`^ ^ a%_x% oIbcx]®­ ,a'`^µ'_{/`^u`][/m w'/`/h mB_B'_ g cI_[%hjw`/`h ¸ ¸ _[ 'r ­ lªb` b {_Bh'`b`aB_i[f Z f Z fIl s w'/`/h ]/b`hB{¬bIµ'Ùg i'´``a/b h'bBi w %/h ] b hIB¬bI j mB_{_Ðn l l rs j×' Z ´B_x ,] b ]%b`hI±jrBr ­ w /`h /]Bb'h g B Z h b'¯x ]Bb hjr2s wexBb'c Z ]%I Z %Bh` a%hj;]/b[h{r9s ¸ ([DPSOHRIGDWDW\SHFRQYHUVLRQDVPD\EHUHTXLUHG Z'Z'Z /h[ cIe[ h[dghxb bI Z _'{bhx jÓ ]Bb'h,r2s SAP AG 2004 The method nextToken() has the return type VWULQJ. It may therefore be necessary to perform data type conversions to further process the extracted tokens. If you want to convert a token to the type int, for example, you call the static method parseInt() from the class ,QWHJHU. int myint = Integer.parseInt(token); © SAP AG JA100 10-39 © SAP AG JA100 10-40 ([HUFLVH 2SWLRQDO 8QLW $SSHQGL[ 7RSLF ,QWHUQDWLRQDOL]DWLRQ At the conclusion of this exercise, you will be able to: • Create multilingual applications 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJLQWHUQDWLRQDOL]DWLRQVRO 3UHOLPLQDU\FRQVLGHUDWLRQV In this exercise, you will create an application in which a language key and a country key are passed as program arguments. Depending on the passed values, the application will output a greeting text and a closing text on the console. 1-1 First, store the text resources for different countries and languages in property files. To begin, in your 0\3URMHFW project generate a new package with the name FRPVDSWUDLQLQJLQWHUQDWLRQDOL]DWLRQH[F and create the following file with the specified contents: 0\5HVRXUFHVSURSHUWLHV greetingKey=Hello byeKey=Good Bye 0\5HVRXUFHVBGHSURSHUWLHV greetingKey=Hallo byeKey=Auf Wiedersehen 0\5HVRXUFHVBGHB&+SURSHUWLHV greetingKey=Grüezie 1-2 In your FRPVDSWUDLQLQJLQWHUQDWLRQDOL]DWLRQH[F packagecreate the class 5HVRXUFH%XQGOH7HVW. Let the wizard create a PDLQmethod for you. In the PDLQ method, a /RFDOH-specific greeting and closing text can be output on the console using the keys “ greetingKey” and “ byeKey”. 1-2-1 © SAP AG The country key and the language key should be passed as program arguments to the application when it is called. Using these passed values, which you can read from the interface parameter of the PDLQ method, instantiate an object of the class MDYDXWLO/RFDOH JA100 10-41 1-2-2 1-2-3 1-3 Then call the static method JHW%XQGOH of the class MDYDXWLO5HVRXUFH%XQGOH and pass to it the basis name of your language resource files, FRPVDSWUDLQLQJLQWHUQDWLRQDOL]DWLRQH[F0\5HVRXUFHV; then pass the /RFDOH object. Finally, call the method JHW6WULQJ for the 5HVRXUFH%XQGOH object that was returned by JHW%XQGOH to output the text of the “ greetingKey” and the “ byeKey” on the console. Test your application with various country and language keys. © SAP AG JA100 10-42 6ROXWLRQ 2SWLRQDO 8QLW $SSHQGL[ 7RSLF ,QWHUQDWLRQDOL]DWLRQ SDFNDJH com.sap.training.internationalization.sol; LPSRUW java.util.Locale; LPSRUW java.util.ResourceBundle; SXEOLF FODVV ResourceBundleTest { SXEOLF VWDWLF YRLG main(String[] args) { Locale locale; LI (args.length == 1) { locale = QHZ Locale(args[0]); } HOVH LI (args.length == 2) { locale = QHZ Locale(args[0], args[1]); } HOVH { locale = Locale.getDefault(); } System.out.println("Language: " + locale.getLanguage()); System.out.println("Country: " + locale.getCountry()); ResourceBundle bundle = ResourceBundle.getBundle( "com.sap.training.internationalization.sol.MyResources", locale); System.out.println(bundle.getString("greetingKey")); System.out.println(bundle.getString("byeKey")); } } MyResources.properties greetingKey=Hello byeKey=Good Bye © SAP AG JA100 10-43 MyResources_de.properties greetingKey=Hallo byeKey=Auf Wiedersehen MyResources_de_CH.properties greetingKey=Grüezie © SAP AG JA100 10-44 ([HUFLVH 2SWLRQDO 8QLW $SSHQGL[ 7RSLF 2EMHFW3HUVLVWHQFH7KURXJK)LOH$FFHVV At the conclusion of this exercise, you will be able to: • Make objects persistent in files by way of serialization 6DPSOHVROXWLRQ: 3URMHFW 6WDUW8S.LW 3DFNDJH FRPVDSWUDLQLQJLRVR 3UHOLPLQDU\FRQVLGHUDWLRQV In this exercise you will write a serialized object to a file. Then you will retrieve the object from the file. 2-1 2-2 2-3 To begin, in your 0\3URMHFW project generate a new package with the name FRPVDSWUDLQLQJLRH[F and create the class &XVWRPHU according to the UML diagram seen below. The constructor of this class should accept values for the two attributes and transfer them into the attributes. In the &XVWRPHU class, implement the Marker-Interface MDYDLR6HULDOL]DEOH to enable serialization of instances in this class. In your FRPVDSWUDLQLQJLRH[F packagecreate the class 6HULDOL]DEOH7HVW. Let the wizard create a PDLQmethod for you. In this PDLQ method, instantiate an object of the class &XVWRPHU. You can select the attribute values of these objects as you wish. Persist the generated &XVWRPHU instance in a file. Choose the directory 1?0\'RFXPHQWV as the storage location for the file to be created. You can choose any name for the file; however, the file name extension must be “ ser” . For this step, use the classes © SAP AG JA100 10-45 )LOH2XWSXW6WUHDP and 2EMHFW2XWSXW6WUHDP. Do not forget to close the file when you are finished with it. 2-4 2-5 Import the persisted object from the file into the program. The classes )LOH,QSXW6WUHDP and 2EMHFW,QSXW6WUHDP are available for this purpose. Output the attribute values of the imported instance on the console to check whether the import transaction was successful. Do not forget to close the file when you are finished with it. Test your application. © SAP AG JA100 10-46 6ROXWLRQ 2SWLRQDO 8QLW $SSHQGL[ 7RSLF 2EMHFW3HUVLVWHQFH7KURXJK)LOH$FFHVV SXEOLF FODVV Customer LPSOHPHQWV Serializable { SULYDWH LQW id; SULYDWH String name; SXEOLF Customer(LQW id, String name) { WKLV.id = id; WKLV.name = name; } SXEOLF String getName() { UHWXUQ name; } SXEOLF LQW getId() { UHWXUQ id; } } SXEOLF FODVV SerializableTest { SXEOLF VWDWLF YRLG main(String[] args) { Customer customer = QHZ Customer(3543, "Maier"); FileOutputStream fos = QXOO; ObjectOutputStream oos = QXOO; WU\ { fos = QHZ FileOutputStream("N:\\My Documents\\test.ser"); oos = QHZ ObjectOutputStream(fos); oos.writeObject(customer); System.out.println( "Customer serialized (file N:\\My Documents\\test.ser)"); © SAP AG JA100 10-47 } FDWFK (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } ILQDOO\ { WU\ { oos.close(); } FDWFK (IOException e) { System.out.println(e.getMessage()); } } customer = QXOO; FileInputStream fis = QXOO; ObjectInputStream ois = QXOO; WU\ { System.out.println("Get it back now:"); fis = QHZ FileInputStream("N:\\My Documents\\test.ser"); ois = QHZ ObjectInputStream(fis); customer = (Customer) ois.readObject(); System.out.println(customer.getId() + " " + customer.getName()); } FDWFK (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } ILQDOO\ { WU\ { ois.close(); } FDWFK (IOException e) { System.out.println(e.getMessage()); } } } } © SAP AG JA100 10-48 ([HUFLVH 2SWLRQDO 8QLW $SSHQGL[ 7RSLF 2EMHFW3HUVLVWHQFH7KURXJK)LOH$FFHVV At the conclusion of this exercise, you will be able to: • Persistently store attribute values in files via character streams • Read file contents via character streams and create objects using the imported values 6DPSOHVROXWLRQ: 3URMHFW 3DFNDJH 6WDUW8S.LW FRPVDSWUDLQLQJLRVR 3UHOLPLQDU\FRQVLGHUDWLRQV In this exercise, you will write possible attribute values for an object of the class &XVWRPHU, which was created in Exercise 2, to a file via a character stream. Then you will import the values written in the file back into the application and use them to generate a &XVWRPHU instance. 1RWH In contrast to Exercise 2, in this exercise persistence is not achieved through object serialization. Consequently, it is not necessary for the class &XVWRPHU to implement the 6HULDOL]DEOH interface. However, to ensure the practicability of the preceding exercise, you should leave the 6HULDOL]DEOH interface in the &XVWRPHU class implemented. 3-1 3-2 3-3 3-4 In your FRPVDSWUDLQLQJLRH[Fpackage, create the class 7H[W)LOH7HVW. Let the wizard create a PDLQmethod for you. In the PDLQ method, store program code for the purpose of writing values for the two attributes of a &XVWRPHU instance in a line of a text file. Use “ |” as a separator for the two values (for example, “ 235|Maier” ). You can choose any name for the file; however, the file name extension must be “ txt” . Choose the directory 1?0\'RFXPHQWV as the storage location for the file to be created. For this step, use the classes )LOH:ULWHU and %XIIHUHG:ULWHU. Do not forget to close the file when you are finished with it. Import the line that was written in the file back into the program. The classes )LOH5HDGHU and %XIIHUHG5HDGHU are available for this purpose. Instantiate an object of the &XVWRPHU class using the line imported from the file. Extract the two attribute values from the imported file using the 6WULQJ7RNHQL]HU class. Before you can pass the received values to the constructor of the &XVWRPHU class via the 6WULQJ7RNHQL]HU, you must first convert the value for the customer number to LQW. © SAP AG JA100 10-49 3-4-1 3-5 Finally, output the attribute values of the generated instance on the console via the corresponding JHW methods of the &XVWRPHU class to check whether your application works correctly. Do not forget to close the file when you are finished with it. Test your application. © SAP AG JA100 10-50 6ROXWLRQ 2SWLRQDO 8QLW $SSHQGL[ 7RSLF 2EMHFW3HUVLVWHQFH7KURXJK)LOH$FFHVV SXEOLF FODVV TextFileTest { SXEOLF VWDWLF YRLG main(String[] args) { FileWriter fw = QXOO; BufferedWriter bw = QXOO; WU\ { fw = QHZ FileWriter("N:\\My Documents\\test.txt"); bw = QHZ BufferedWriter(fw); bw.write("235|Maier"); System.out.println("File N:\\My Documents\\test.txt created!"); } FDWFK (IOException e) { System.out.println(e.getMessage()); } ILQDOO\ { WU\ { bw.close(); } FDWFK (IOException e) { System.out.println(e.getMessage()); } } FileReader fr = QXOO; BufferedReader br = QXOO; String line; WU\ { System.out.println("Get the data back and ..."); fr = QHZ FileReader("N:\\My Documents\\test.txt"); br = QHZ BufferedReader(fr); line = br.readLine(); System.out.println( "... use it to instantiate an object:"); © SAP AG JA100 10-51 StringTokenizer st = QHZ StringTokenizer(line, "|"); LQW id = Integer.parseInt(st.nextToken()); String name = st.nextToken(); Customer customer = QHZ Customer(id, name); System.out.println(customer.getId() + " " + customer.getName()); } FDWFK (Exception e) { System.out.println(e.getMessage()); } ILQDOO\ { WU\ { br.close(); } FDWFK (IOException e) { System.out.println(e.getMessage()); } } } } © SAP AG JA100 10-52