BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
Transcript of BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 1/505
BC401ABAP Objects
.
INSTRUCTOR HANDBOOKINSTRUCTOR-LED TRAINING
Course Version: 10Course Duration: 5 Day(s)Material Number: 50110523
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 2/505
SAP Copyrights and Trademarks
© 2012 SAP AG. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or for any purposewithout the express permission of SAP AG. The information contained herein may bechanged without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietarysoftware components of other software vendors.
● Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of
Microsoft Corporation.
● IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System
x, System z, System z10, System z9, z10, z9, iSeries, pSeries, xSeries, zSeries, eServer,
z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise
Server, PowerVM, Power Architecture, POWER6+, POWER6, POWER5+, POWER5,
POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS,
HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, Parallel Sysplex, MVS/ESA,AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or
registered trademarks of IBM Corporation.
● Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
● 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.
● SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects
Explorer, StreamWork, 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 other countries.
● Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports,
Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and
services mentioned herein as well as their respective logos are trademarks or
registered trademarks of Business Objects Software Ltd. Business Objects is an SAP
company.
● Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybase
products and services mentioned herein as well as their respective logos are
trademarks or registered trademarks of Sybase, Inc. Sybase is an SAP company.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 3/505
All other product and service names mentioned are the trademarks of their respectivecompanies. Data contained in this document serves informational purposes only. Nationalproduct specifications may vary.
These materials are subject to change without notice. These materials are provided by SAP AGand its affiliated companies ("SAP Group") for informational purposes only, withoutrepresentation or warranty of any kind, and SAP Group shall not be liable for errors oromissions with respect to the materials. The only warranties for SAP Group products andservices are those that are set forth in the express warranty statements accompanying suchproducts and services, if any. Nothing herein should be construed as constituting an additionalwarranty.
© Copyright . All rights reserved. iii
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 4/505
iv © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 5/505
About This Handbook
This handbook is intended to complement the instructor-led presentation of this course, and serve as asource of reference. It is not suitable for self-study.
Typographic Conventions
American English is the standard used in this handbook.
The following typographic conventions are also used.
This information is displayed in the instructor’s presentation
Demonstration
Procedure
Warning or Caution
Hint
Related or Additional Information
Facilitated Discussion
User interface control Example text
Window title Example text
© Copyright . All rights reserved. v
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 6/505
vi © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 7/505
Contents
xi Course Overview
1 Unit 1: Introduction to Object-Oriented Programming
2 Lesson: Explaining the Object-Oriented Programming Model 30 Minutes13 Lesson: Analyzing and Designing with Unified Modeling Language
(UML)40 Minutes
25 Exercise 1: Create UML Diagrams 20 Minutes
37 Unit 2: Fundamental Object-Oriented Syntax
39 Lesson: Creating Local Classes 90 Minutes53 Exercise 2: Create Local Classes 30 Minutes
60 Lesson: Creating and Working with Objects 45 Minutes67 Exercise 3: Create Objects 15 Minutes71 Lesson: Accessing Methods and Attributes 60 Minutes77 Exercise 4: Call Methods 30 Minutes85 Lesson: Implement Constructors in Local Classes 60 Minutes89 Exercise 5: Create and Use Constructors 30 Minutes96 Lesson: Implementing Class Constructors in Local Classes 60 Minutes99 Exercise 6: Create and Use Static Constructors 30 Minutes
117 Unit 3: Inheritance and Casting
118 Lesson: Implementing Inheritance 90 Minutes127 Exercise 7: Implement Inheritance 45 Minutes140 Lesson: Implementing Up-Casts Using Inheritance 35 Minutes145 Exercise 8: Implement Up-Casts 35 Minutes151 Lesson: Implementing Polymorphism Using Inheritance 60 Minutes155 Exercise 9: Implement Polymorphism Using Inheritance 30 Minutes162 Lesson: Implementing Down-Casts Using Inheritance 50 Minutes167 Exercise 10: Implement Down-Casts 20 Minutes
185 Unit 4: Interfaces and Casting
186 Lesson: Defining and Implementing Local Interfaces 70 Minutes193 Exercise 11: Define and Implement a Local Interface 30 Minutes204 Lesson: Implement Polymorphism Using Interfaces 60 Minutes209 Exercise 12: Implement Polymorphism Using Interfaces 30 Minutes220 Lesson: Joining Classmodels Using Interfaces 40 Minutes223 Exercise 13: Join Classmodels Using Interfaces 20 Minutes
© Copyright . All rights reserved. vii
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 8/505
241 Unit 5: Object-Oriented Events
242 Lesson: Implementing Events in Local Classes 70 Minutes251 Exercise 14: Implement Events in Local Classes 30 Minutes256 Lesson: Implementing Events in Local Interfaces 30 Minutes257 Exercise 15: Implement Event Handling for Interfaces 10 Minutes
269 Unit 6: Object-Oriented Repository Objects
270 Lesson: Creating Global Classes 75 Minutes281 Exercise 16: Implement a Global Class 30 Minutes286 Lesson: Defining and Implementing Global Interfaces 50 Minutes289 Exercise 17: Import and Implement a Global Interface 20 Minutes294 Lesson: Implementing Inheritance in Global Classes 50 Minutes301 Exercise 18: Implement Inheritance in Global Classes 20 Minutes
311 Unit 7: ABAP Object-Oriented Examples312 Lesson: Implementing ABAP List Viewer 120 Minutes319 Exercise 19: Implement the ALV Grid Control 30 Minutes327 Exercise 20: Implement a Popup with the ALV Grid Control 30 Minutes339 Lesson: Describing Business Add-Ins 20 Minutes
351 Unit 8: Object-Oriented Design Patterns
353 Lesson: Implementing Special Object-Oriented Techniques 30 Minutes361 Lesson: Implementing the Singleton Pattern 45 Minutes
365 Exercise 21: Implement the Singleton Pattern 20 Minutes376 Lesson: Implementing Factory Classes Using Friendship 45 Minutes379 Exercise 22: Implement a Factory Class Using Friendship 20 Minutes386 Lesson: Implementing Persistent Objects 45 Minutes
403 Unit 9: Object-Oriented Exception Handling
404 Lesson: Explaining Class-Based Exception Handling 20 Minutes411 Lesson: Defining and Raising Exceptions 75 Minutes419 Exercise 23: Implement Class-Based Exceptions 45 Minutes426 Lesson: Implementing Advanced Exception Handling Techniques 60 Minutes
435 Exercise 24: Map Exceptions to Each Other 45 Minutes
449 Unit 10: Run Time Type Services
450 Lesson: Implementing Run Time Type Identification 60 Minutes455 Exercise 25: Query Object Type Properties at Runtime 30 Minutes458 Lesson: Implementing Run Time Type Creation 60 Minutes
465 Unit 11: Advanced ABAP Object-Oriented Techniques
466 Lesson: Explaining Advanced ABAP Object-Oriented Techniques 45 Minutes
viii © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 9/505
477 Unit 12: Case Study
478 Lesson: Developing Object-Oriented Case Study 330 Minutes483 Exercise 26: Create an UML Class Diagram 20 Minutes487 Exercise 27: Create an UML Class Diagram 300 Minutes
© Copyright . All rights reserved. ix
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 10/505
x © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 11/505
Course Overview
TARGET AUDIENCE
This course is intended for the following audiences:● Application Consultant
● Data Consultant
● Development Consultant
● Industry / Business Analyst Consultant
● Support Consultant
● Technology Consultant
● Developer
© Copyright . All rights reserved. xi
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 12/505
xii © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 13/505
UNIT 1 Introduction to Object-OrientedProgramming
Lesson 1
Explaining the Object-Oriented Programming Model 2
Lesson 2
Analyzing and Designing with Unified Modeling Language (UML) 13Exercise 1: Create UML Diagrams 25
UNIT OBJECTIVES
● Differentiate procedural and object-oriented programming models
● Describe ABAP Objects
● Apply classification
● Model in UML
© Copyright . All rights reserved. 1
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 14/505
Unit 1Lesson 1
2Explaining the Object-Oriented Programming
Model
LESSON OVERVIEWThis lesson gives you an overview of concepts related to programming with ABAP, using theobject-oriented approach.
Finding the best way to handle this lesson depends on the individual group of participants.Experience shows that participants often have some previous knowledge of proceduralprogramming, particularly the contents of the previous course, BC400. Sometimes, theseparticipants hesitate to use object orientation. Try to overcome this hesitation.
It would be, therefore, counterproductive to put too much emphasis on the last section. Theattributes described in that section need gradual dealing with in the specific lessons. The finalsection is more suitable for participants with object-oriented programming experience inother languages. You can assure these participants that you will soon reintroduce them tosome familiar concepts.
It is important to clarify that the object-oriented programming model does not extend therange of problems that you can solve algorithmically. Object orientation is just anotherprogramming approach. It can solve exactly the same number of problems as otherapproaches.
Business Example
You must explain the basics of the object-oriented programming model and its advantages toyour development project manager. For this reason, you require the following knowledge:
● An understanding of procedural programming
● An understanding of ABAP objects
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Differentiate procedural and object-oriented programming models
● Describe ABAP Objects
2 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 15/505
History of Selected Programming Languages
Figure 1: History of Selected Programming Languages
You should repeat the points mentioned below whenever they are relevant throughout theentire course and illustrate them with specific syntax examples to ensure that theparticipants do not merely see them as empty phrases.
You can see from the Simula 67 programming language, object-oriented programming wasdeveloped at approximately the same time as the logical and procedural programming
models. In the past, COBOL and the procedural programming model as expressed inlanguages, such as C or Pascal, were dominant in enterprise application development. BeforeABAP, SAP originally used a macro assembler.
Even today, many developers still have more experience with procedural programming thanobject-oriented programming. Therefore, introduction to object-oriented programming alsouses references to the procedural model in its explanations.
ABAP was created with the intention of improving reporting. It was developed relativelyindependently as an in-house programming language, although other programminglanguages, like COBOL and PASCAL, influenced it. ABAP/4 was then extended to form ABAPObjects. Therefore, ABAP Objects unite object-oriented and procedural elements in oneprogramming language. For the object-oriented part, only those object-oriented conceptsthat had proved their worth for enterprise application development in other languages, suchas Java, C++, and Smalltalk, were adopted by ABAP. ABAP Objects, such as ABAP/4 or theversion before it, also contains some unique and advantageous concepts.
Lesson: Explaining the Object-Oriented Programming Model
© Copyright . All rights reserved. 3
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 16/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 17/505
Encapsulation Using Function Groups
Figure 4: Encapsulating Data Using Function Groups
It may be helpful to mention some other characteristics of function modules, such as remotecapability or optional parallelization. In doing so, you risk being drawn away from the coresubject matter, but you will be able to emphasize the power and versatility of even theprocedural part of ABAP Objects.
It can also help participants understand that object orientation is just another programmingmethod and does not necessarily lead to more technical possibilities.
Every time a main program calls a function module, the entire function module is loaded tothe internal session. The function group remains active until the main program finishesexecuting. The system stores the main program and the called function groups in separatememory areas. Nothing is shared even if the data objects of the function groups have thesame name.
You can only call the function modules of the function groups from the main program. In turn,the function modules can access the other components, particularly the global data of thefunction groups. In other words, it is not possible to access the global data of function groupdirectly from the main program.
Encapsulation also incorporates the idea that the implementation of a service can be hiddenfrom the other components of the system, so that these components cannot do and not haveto make assumptions about the internal status of the modularization unit. In this way, thedesign of these other components is not dependent on a specific implementation of the othermodularization units.
Therefore, a function group is a unit of data and functions that manages the data.Encapsulated access to data and services is one of the many concepts of the object-orientedprogramming model. Therefore, the procedural part of ABAP Objects can support it. Hence,you can implement Bridge Application Program Interface (BAPIs) as function modules andBusiness Objects as function groups.
Lesson: Explaining the Object-Oriented Programming Model
© Copyright . All rights reserved. 5
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 18/505
Function Group
Figure 5: Example of a Function Group
The fictional function group S_VEHICLE provides a user or client with the servicesINC_SPEED, DEC_SPEED, and GET_SPEED. These services are the interface of the functiongroup and access the global data object SPEED, which belongs to the whole function group.
Usage of Function Group
Figure 6: Example of Using the Function Group
The best way to learn about the object-oriented program concepts is to highlight thedifferences between the new characteristics mentioned above and the old characteristics.Multiple instantiation is a new characteristic that could be suitable for this purpose. Someother object-oriented concepts also exist in procedural languages or they are easy toimagine.
Unit 1: Introduction to Object-Oriented Programming
6 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 19/505
However, this is not the case for inheritance. It is more difficult and, therefore, less suitablefor defining the limits of the object-oriented approach.
The main program cannot access the data object SPEED of the function group directly.
Multiple Instantiation
Figure 7: Several Instances of One Function Group
If the main program is to work with several vehicles, this action is not possible without extraprogramming and administrative effort. Most importantly, a whole function group can nolonger represent one specific vehicle.
Multiple Instantiation in Object-Oriented Programming
Figure 8: Multiple Instantiation in Object-Oriented Programming
The possibility of creating several runtime instances in a capsule for each program context isone of the key characteristics of object-oriented programming.
In this example, you create four vehicles all of which have different characteristic instances.
However, they all share the same data structure, the same range of functions, and the abilityto protect their data against access from outside.
Lesson: Explaining the Object-Oriented Programming Model
© Copyright . All rights reserved. 7
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 20/505
ABAP Main Memory and Encapsulation
Figure 9: ABAP Main Memory and Encapsulation
The features of Encapsulation are as follows:● Modularization units for encapsulating functions and possibly data.
● Work with the global data of the main program.
● Create objects for encapsulating functions and data.
● Do multiple instantiation.
Like the function groups, the objects are also stored in the same internal sessions of theprogram in use. All data areas are also separate from each other, which keeps themprotected.
Data Management in Procedural and Object-Oriented Models
Figure 10: Data Management in Procedural and Object-Oriented Models – Summary
Unit 1: Introduction to Object-Oriented Programming
8 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 21/505
Unlike in procedural programming, the use of multiple instantiation in object-orientedprogramming allows you to create a direct abstraction of a real object. The establishedconcept of encapsulation was systematically extended in the process.
ABAP Objects
Figure 11: ABAP Objects as a Compatible Extension of ABAP
The object-oriented concepts of ABAP Objects are the same as those concepts of othermodern object-oriented languages like C++ or Java. ABAP Objects did not include fewconcepts that did not prove to be successful in other languages. On the other hand, ABAPObjects also has helpful language elements that C++ and Java do not offer. Some specificfeatures of ABAP Objects only exist because of the guaranteed upward compatibility of older
ABAP language elements. Major differences in comparison to other object-orientedlanguages are in the development environment. You can use the entire range of functions ofthe ABAP Workbench with ABAP Objects.
You can use ABAP Objects statements in procedural ABAP programs. Objects (classes)contain procedural ABAP statements.
In the object-oriented context, ABAP Objects has the following features:● Only object-oriented concepts that have proved useful
● The use of type checks
● Obsolete statements are prohibited in the object-oriented context
Developing ABAP Objects
It may be useful to mention the advantages of SAP’s approach. Upward compatibility savesdevelopers from carrying out a migration when the developers have to implement a newrelease. With a small number of exceptions, you can still use the repository objects from thefirst SAP R/3 Basis release without restrictions in SAP Web AS 6.20. No competitor canmatch this.
ABAP Objects are not a new language but has been designed as a systematic extension ofABAP. All of the extensions, including the old procedural parts, are upwardly compatible.
Type checks in the object-oriented contexts of ABAP Objects are stricter than those approachin the procedural contexts.
Lesson: Explaining the Object-Oriented Programming Model
© Copyright . All rights reserved. 9
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 22/505
In developing ABAP Objects, the ABAP language was cleaned up, particularly in the object-oriented contexts. This means that obsolete statements lead to syntax errors. However, it isalso advisable to avoid obsolete statements in the purely procedural environment, as thisaction creates safer and more flexible source texts. Nevertheless, because the language isupwardly compatible, it is not possible to prevent the use of such statements entirely.
For a list of obsolete language elements, refer to the ABAP keyword documentation. ABAPspecifically notes each of the obsolete statements as forbidden in the object-oriented context.
Client/Server Relationship Between Objects
Figure 12: Client/Server Relationships Between Objects
Objects behave like client/server systems when one object sends a message to anotherobject, telling it to behave in a certain way; the first object can be seen as a client and theother as a server.
To be able to separate requests and deliveries of services, the following conditions mustbe true:● The client object must adhere to the protocol of the server object.
● The protocol of server object must be clear, so that a potential client can follow it withoutany problems.
Objects can perform both roles simultaneously. They can offer services to other objects whilerequesting services at the same time.
In object-oriented programming, the services are distributed among the objects in such a waythat there are no redundancies and so that each object offers exactly those services that arewithin its area of responsibility. If an object needs any other services, it requests theseservices from other objects. This concept is known as the principle of delegation of tasks.
Client/Server Relationship – Example
The developer should distribute the common task of data retrieval and output over at leasttwo objects. One is responsible for data retrieval and one for output. As long as the dataretrieval object does not change its protocol, the developer can alter its internalimplementation, without any changes to the output object becoming necessary.
Alternatively, a different object could even replace the data retrieval object, if the new objectuses the same protocol. These exchanges can also take place at runtime.
Unit 1: Introduction to Object-Oriented Programming
1 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 23/505
Additional Concepts of the Object-Oriented Programming Model
Figure 13: Additional Concepts of the Object-Oriented Programming Model
The additional concepts of the object-oriented programming model are as follows:● Inheritance
Inheritance defines the implementation relationships between classes, so that one class(subclass) adopts the structure and behavior of another class (superclass), possibly alsoadapting or extending it.
● Polymorphism
In object-orientation, polymorphism is when instances of different classes responddifferently to the same messages.
● Event control
Instead of sending messages directly to specific objects, objects can also trigger events.Events can be triggered if it is not yet known at the time of development if objects reacts,and if so, how they react.
Features of Object-Orientation
The features of object-orientation will only become apparent to the participants after they
have completed the relevant lessons.
The object-oriented programming model of ABAP Objects has the following keycharacteristics:● Objects are a direct abstraction of the real world.
● Objects are units made up of data and the functions belonging to that data.
● Processes can be implemented realistically.
The advantages of the object-oriented programming model over the proceduralprogramming model are as follows:● Improved software structure and consistency in the development process
Lesson: Explaining the Object-Oriented Programming Model
© Copyright . All rights reserved. 11
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 24/505
● Reduced maintenance effort and less susceptibility to errors
● Better integration of the customer or user into the analysis, design, and maintenanceprocess
● Simpler and more secure extension of the software
A standardized language is used in the various phases of software development (analysis,specification, design, and implementation). Communication is much easier when changingbetween phases.
The Software Development Process
Figure 14: The Software Development Process
In object-oriented programming, analysis and design decisions have greater effect on theimplementation than they have in procedural programming.
Therefore, you should already structure and formally standardize the analysis and designphase. You can use modeling languages to do this analysis and design phase.
LESSON SUMMARYYou should now be able to:
● Differentiate procedural and object-oriented programming models
● Describe ABAP Objects
Unit 1: Introduction to Object-Oriented Programming
12 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 25/505
Unit 1Lesson 2
12Analyzing and Designing with Unified Modeling
Language (UML)
LESSON OVERVIEWThis lesson explains how to develop an object-oriented solution to a business applicationproblem. In addition, it also explains how to classify your objects and define the relationshipsbetween them.
In this lesson, it is important to make clear distinctions between modeling concepts and therelated programming concepts. For example, when looking at class diagram, you often speakof inheritance, although you actually mean a generalization/specialization relationship. Thisrequires strict discipline, especially from people who are new to the subject matter and maystill be somewhat unsure. For the moment, you are only dealing with modeling.
Business Example
Model a business application requirement before you implement the business application. Forthis reason, you require the following knowledge:
● Class diagram
● Object diagram
● Sequence diagram
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Apply classification
● Model in UML
© Copyright . All rights reserved. 13
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 26/505
Classification of Objects
Figure 15: Classification of Objects
With object-oriented programming, you view the real world as a collection of objects. Forexample, different airplanes, cars, and people. Some of these objects are similar. In otherwords, you can describe them using the same characteristics and they exhibit the samebehavior.
You can now group all characteristics and behavior of these similar objects now into onecentral class. This class is used to describe every object that derives from it. A class is
therefore a description of a quantity of objects that are typified by the same characteristicsand the same behavior.
For example, the vehicle "make x, ..., series n", is an object of class car. This object is thereforea concrete instance of its class. So, an object has an identity, a status (number ofcharacteristic instances), and a behavior. Do not confuse the concepts of identity and status.
Identity is an attribute that distinguishes each object from all other objects of its class. Twodifferent objects can have identical attribute values and still not be identical. For example, twocoffee cups have the same height and diameter, have the same handle, and are both white.Although their statuses are completely identical, they are clearly two different coffee cups.
Literature on the subject of object orientation speaks of instances. This instance simply
means an object.
Note:Repeat these points whenever they are relevant throughout the entire course andillustrate them with specific syntax examples to ensure that they are not merelyseen as empty phrases.
Unit 1: Introduction to Object-Oriented Programming
14 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 27/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 28/505
Comparison of Classes and Objects
Figure 17: Comparison of Classes and Objects
A sure understanding of the relationship between classes and objects, as summarized hereagain, is a prerequisite for proceeding with the following lessons successfully.
A summary of relationships between class and object is as follows:
Class Object
It is a general description of objects It represents part of the real world
It specifies status data and behavior It is a concrete form, a specimen, or aninstance of a class
Class DiagramUML is a globally standardized modeling language. You use it for the specification,construction, visualization, and documentation of models for software systems. In addition,UML enables uniform communication between users. UML is an industry standard and hasbeen developed by the Object Management Group (OMG) since September 1997. SAP uses
UML as the company-wide standard for object-oriented modeling. For more information onthe UML specifications, see http://www.omg.org on the OMG homepage.
UML describes a number of different diagram types to represent different views of a system.
Three important diagram types to represent different views of a system are as follows:● Class diagrams
Shows the classes and the relationships between them, that is, a static view of a model.
● Behavior diagrams
Pay particular attention to the sequence in which the objects relate to each other.
●
Component diagrams
Unit 1: Introduction to Object-Oriented Programming
16 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 29/505
Show the organization and dependencies of components.
Find concrete methods for realizing the first two aspects in the list of the programminglanguage.
The third aspect is realized in the repository object package. In other words, you can usepackages to realize the structure of software components within SAPWeb according to thespecification of structure in a component diagram.
Class Representation
Figure 18: Representation of a Class
In UML notation, a rectangle represents a class. First, the name of the class is given, then itsattributes are given, and finally, its methods are given. However, you also have the option ofomitting the attribute part and/or the method part.
Attributes describe the data that you can store in the objects of a class. They also determinethe status of an object. Methods describe the functions that an object can perform. Theytherefore determine the behavior of the object.
Class Diagram Example
Figure 19: An Example of a Class Diagram
Lesson: Analyzing and Designing with Unified Modeling Language (UML)
© Copyright . All rights reserved. 17
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 30/505
For the modeler of this example, a vehicle is a car with 4 wheels. Of course, the example ofcar rental companies and cars could also have been described and modeled differently.
In addition, explain to the participants that modeling in object-oriented program is only dealtwith in a basic way. It is advisable that after the course the students should go into thissubject in greater depth and acquire more literature on the subject. The topic of modeling isdealt with in this course on learning-by-doing basis.
A class diagram describes all static relationships between the classes.
The two basic forms of static relationships are as follows:● Association
For example, a customer books a car at a rental car company.
● Generalization/Specialization
For example, a car, a bus, and a truck are all vehicles.
Note:Classes can also be shown in class diagrams with their attributes and methods.Here, these attributes and methods have been left out to improve clarity.
Association
Figure 20: Association
An association describes a semantic relationship between classes. The specific relationshipbetween objects in these classes is known as an object link. Object links are therefore theinstances of associations.
An association is a relationship between different classes (binary association). However, anassociation can also be recursive; in this case, the class would have a relationship with itself.
In most cases, recursive associations are used to link two different objects in one class. Thepoints assume that the associations are binary.
Unit 1: Introduction to Object-Oriented Programming
18 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 31/505
Each association has two roles, one for each direction of the association. Each role can bedescribed with an association name. Each role has a cardinality that shows how manyinstances can participate in this relationship. The multiplicity is the number of participatingobjects in one class that have a relationship to an object in the other class. Like all otherelements of the model, cardinalities are dependent on the concrete situation that is beingmodeled.
In this example, you could also require a cardinality of at least one, to indicate that only aperson who actually makes a booking becomes a customer of the rental car company. On theother hand, the cardinality of any number would allow for a more general definition of acustomer.
Following are the points to be remembered for representing association:● Represent an association between class symbols by drawing a line between them.
● Specify the cardinality (also referred to as multiplicity) of the relationship at each end ofthe line.
● Use arrows to indicate the navigation options, that is, the accessibility of the associationpartner.
● Write the association name in italics above the line, and the name may contain an arrow toshow the read direction.
● Enter role names at the end of the lines, if the modeler defines roles for both partners.
Inform the participants that you will now be providing some additional detailed examples ofassociations to demonstrate the options for modeling with class diagrams. However, for therest of the course you will not mention again the recursive and multiple associations andassociation classes and you will not use them in the exercises.
Nevertheless, one objective of this course is to learn how to distinguish between association,aggregation/composition, and generalization/specialization. It is important that theparticipants have understood the difference between aggregation/composition andgeneralization/specialization.
Lesson: Analyzing and Designing with Unified Modeling Language (UML)
© Copyright . All rights reserved. 19
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 32/505
Association with Roles Example
Figure 21: Examples of Association with Roles
In the example of multiple associations, use the role names at the end of the association linesto describe in detail the relationships between the classes involved. A person appears in therole of an employee or of a company director.
In the recursive association shown here, the two roles of child and parent are similarly definedusing role names. Two instances of the LCL_PERSON class thus have a relationship with eachother and represent two roles.
Association Classes
Figure 22: Association Classes
If association is used to link two classes, then this relationship can be better represented by a
special class.
Unit 1: Introduction to Object-Oriented Programming
2 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 33/505
The various characteristics of the relationship are described using the attributes of theassociation class. A dotted line connects this additional class to the association line.
Aggregation and Composition
Figure 23: Aggregation and Composition
Aggregation and composition are specializations of association. They show that an objectconsists of other objects or contains other objects (composition part). Aggregation is aspecial case of association–a whole–part relationship. You can describe the relationship withthe words consists of or is a part of. For example, a car consists of wheels, among otherthings.
Aggregation and composition are displayed as a line between two classes that is labeled witha small rhombus. The rhombus indicates the aggregate, that is, the composition. Otherwise,
the notation conventions are the same as used for associations.Composition is a specialization of aggregation. It is an existence-dependent and whole - partrelationship. Composition means that the contained object cannot exist without theaggregation (for example, a car reservation cannot exist without the car rental). Therefore,the cardinality of the aggregate can only be exactly one. The lifetime of the individual parts islinked to the lifetime of the aggregate, meaning parts are created either with or after theaggregate and are destroyed either with or before the aggregate.
Lesson: Analyzing and Designing with Unified Modeling Language (UML)
© Copyright . All rights reserved. 21
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 34/505
Generalization and Specialization
Figure 24: Generalization and Specialization
Generalization and specialization relationships are always bidirectional. You can describegeneralization with the words "is a special". A triangular arrow indicates generalization orspecialization relationships. This arrow always points to the more general class. The level ofgeneralization increases in the direction of the arrow. Trees can be built up using many ofthese relationships.
Object Diagram
Figure 25: An Object Diagram
An object diagram is a snapshot taken during program execution, which describes the
instances of the classes and the relationships between them. It is not a new type of diagram.
Unit 1: Introduction to Object-Oriented Programming
22 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 35/505
Rather, it is a variant of the class diagram and is only useful for representing a complex classdiagram.
Here, you can use the optional exercise relating to object diagrams to underline thedifference between classes and objects.
Explain the structure of the exercise on object diagrams. There are eight possible objectdiagrams for a class diagram, although some of these object diagrams are incorrect. Theparticipants should determine the right and the wrong object diagrams in a form of multiplechoices.
The sequence diagrams complete the unit on modeling. You do not mention again thesequence diagrams for the rest of the course. There is no exercise for this concept.
Sequence Diagram
Figure 26: A Sequence Diagram
Sequence diagrams are used to display certain processes or situations. Sequence diagramfocus on the time sequence of the behavior.
Time sequence of the behavior of object is as follows:● Creating and deleting objects
● Exchanging messages between objects
In UML notation, you can represent the object lifeline by dotted vertical lines with a box
containing the object name at the top. An "X" marks the end of the lifeline. The control focus isshown as a vertical rectangle on the object lifeline. The control focus shows the active periodof the object.
Statuses of an object are as follows:● An object is active when actions are executed.
● An object is indirectly active if it is waiting for a subordinate procedure to end.
Messages are shown as horizontal arrows between the object lines. The message is writtenabove the arrow in the form parameter. There are various ways of representing the reply; inthis example, it is shown as a dotted returning arrow. You can also include a description of theprocess and add comments to the object lifeline, as required.
Lesson: Analyzing and Designing with Unified Modeling Language (UML)
© Copyright . All rights reserved. 23
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 36/505
Delegation Principle
Figure 27: Delegation Principle in Sequence Diagram
In delegation, handling a request involves two objects. The recipient of the request delegatesthe execution of the request to a delegate. In this example, the driver (object DRIVER) sendsthe message GET_FUEL_LEVEL to the vehicle (object CAR). The receipt of this messagecauses the car to send a message to the tank (object TANK) to find out what the tankcontains. In other words, the car delegates this task to the tank. If necessary, the car formatsthe information containing the current value of the tank contents before it passes it back tothe driver.
Unit 1: Introduction to Object-Oriented Programming
24 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 37/505
Unit 1Exercise 1
23Create UML Diagrams
Business Example
You are a modeler for an airline corporation that owns several airline carriers. Start modelinga simple airplane management that can manage the airline carriers and their airlines. For thisreason, you must be able to design simple UML class diagrams and model basic objectclassifications.
As a modeler, create a model for a simple airplane management that contains classes withattributes and methods that contains suitable association types and suitable cardinalities.
1. Create an UML class diagram containing the following classes:
Class Name Description
LCL_CARRIER For the Airline Companies
LCL_AIRPLANE For the Airline Companies
LCL_PASSENGER_PLANE For Passenger Planes
LCL_CARGO_PLANE For Cargo Planes
2. Create some appropriate attributes and methods for each class.
3. Define relationships between your classes and choose suitable association types.
4. Choose suitable cardinalities.
As a modeler, decide whether the given object diagrams are correct.
The advantage of this exercise is that it gives the participants another opportunity to practice(with your help) distinguishing between classes and objects. You should therefore includethis exercise if you have enough time.
1. A class diagram is shown in the figure. Eight object diagrams are drawn for this classdiagram. Decide whether each object diagram is correct and check if the provided box iscorrect.
© Copyright . All rights reserved. 25
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 38/505
Figure 29: Possible Object Diagrams (1)
Figure 30: Possible Object Diagrams (2)
Unit 1: Introduction to Object-Oriented Programming
26 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 39/505
Unit 1Solution 1
25Create UML Diagrams
Business Example
You are a modeler for an airline corporation that owns several airline carriers. Start modelinga simple airplane management that can manage the airline carriers and their airlines. For thisreason, you must be able to design simple UML class diagrams and model basic objectclassifications.
As a modeler, create a model for a simple airplane management that contains classes withattributes and methods that contains suitable association types and suitable cardinalities.
1. Create an UML class diagram containing the following classes:
Class Name Description
LCL_CARRIER For the Airline Companies
LCL_AIRPLANE For the Airline Companies
LCL_PASSENGER_PLANE For Passenger Planes
LCL_CARGO_PLANE For Cargo Planes
a) Use the model solution as a guide.2. Create some appropriate attributes and methods for each class.
a) Contain the general attributes and methods for the airplanes in LCL_AIRPLANE.
b) Use model solution as a guide.
3. Define relationships between your classes and choose suitable association types.
a) A generalization/specialization relationship between LCL_AIRPLANE andLCL_PASSENGER_PLANE or LCL_CARGO_PLANE seems to be appropriate. Anaggregation should exist between LCL_AIRPLANE and LCL_CARRIER.
b) Use the model solution as a guide.
4. Choose suitable cardinalities.
a) You can you various cardinalities in this case. Use the relevant sections of the lessonand the model solution as a guide.
© Copyright . All rights reserved. 27
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 40/505
Figure 28: Class Diagram for Exercise – CARRIER/AIRPLANE
As a modeler, decide whether the given object diagrams are correct.
The advantage of this exercise is that it gives the participants another opportunity to practice(with your help) distinguishing between classes and objects. You should therefore includethis exercise if you have enough time.
1. A class diagram is shown in the figure. Eight object diagrams are drawn for this classdiagram. Decide whether each object diagram is correct and check if the provided box iscorrect.
Unit 1: Introduction to Object-Oriented Programming
28 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 41/505
Figure 29: Possible Object Diagrams (1)
Figure 30: Possible Object Diagrams (2)
a) The object diagrams numbered 2, 4, 5, 6, and 8 are correct.
Lesson: Analyzing and Designing with Unified Modeling Language (UML)
© Copyright . All rights reserved. 29
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 42/505
LESSON SUMMARYYou should now be able to:
● Apply classification
● Model in UML
Unit 1: Introduction to Object-Oriented Programming
3 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 43/505
Unit 1
29Learning Assessment
1. A ______________ program consists of type definitions and data declarations.
Choose the correct answer.
X A object-oriented ABAP
X B procedural ABAP
X C object-oriented
X D procedural
2. Data and functions are kept separate in the procedural programming model.
Determine whether this statement is true or false.
X True
X False
3. Every time a main program calls in a function module, the internal session does not loadits function group.
Determine whether this statement is true or false.
X True
X False
4. What does multiple instantiation mean?
Choose the correct answer.
X A Creating and managing any number of runtime instances
X B Implementing relationships between classes
X C Creating instances of different classes
X D Sending messages directly to specific objects by triggering events
© Copyright . All rights reserved. 31
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 44/505
5. Which of the following defines the instances of different classes that respond differently tothe same messages?
Choose the correct answer.
X A Inheritance
X B Polymorphism
X C Encapsulation
X D Event control
6. Which of the following is a simplification of complex relationships in the real world?
Choose the correct answer.
X A Inheritance
X B Abstractions
X C Encapsulation
X D Event control
7. The ______________ diagram pays particular attention to the sequence in which theobjects relate to each other.
Choose the correct answer.
X A class
X B behavior
X C component
X D object
8. You can group all characteristics and behavior of similar objects into one central class.
Determine whether this statement is true or false.
X True
X False
9. In delegation, handling a request involves three objects.
Determine whether this statement is true or false.
X True
X False
Unit 1: Learning Assessment
32 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 45/505
Unit 1
31Learning Assessment- Answers
1. A ______________ program consists of type definitions and data declarations.
Choose the correct answer.
X A object-oriented ABAP
X B procedural ABAP
X C object-oriented
X D procedural
2. Data and functions are kept separate in the procedural programming model.
Determine whether this statement is true or false.
X True
X False
3. Every time a main program calls in a function module, the internal session does not loadits function group.
Determine whether this statement is true or false.
X True
X False
4. What does multiple instantiation mean?
Choose the correct answer.
X A Creating and managing any number of runtime instances
X B Implementing relationships between classes
X C Creating instances of different classes
X D Sending messages directly to specific objects by triggering events
© Copyright . All rights reserved. 33
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 46/505
5. Which of the following defines the instances of different classes that respond differently tothe same messages?
Choose the correct answer.
X A Inheritance
X B Polymorphism
X C Encapsulation
X D Event control
6. Which of the following is a simplification of complex relationships in the real world?
Choose the correct answer.
X A Inheritance
X B Abstractions
X C Encapsulation
X D Event control
7. The ______________ diagram pays particular attention to the sequence in which theobjects relate to each other.
Choose the correct answer.
X A class
X B behavior
X C component
X D object
8. You can group all characteristics and behavior of similar objects into one central class.
Determine whether this statement is true or false.
X True
X False
Unit 1: Learning Assessment- Answers
34 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 47/505
9. In delegation, handling a request involves three objects.
Determine whether this statement is true or false.
X True
X False
Unit 1: Learning Assessment- Answers
© Copyright . All rights reserved. 35
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 48/505
Unit 1: Learning Assessment- Answers
36 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 49/505
UNIT 2 Fundamental Object-OrientedSyntax
Lesson 1
Creating Local Classes 39Exercise 2: Create Local Classes 53
Lesson 2
Creating and Working with Objects 60
Exercise 3: Create Objects 67
Lesson 3
Accessing Methods and Attributes 71Exercise 4: Call Methods 77
Lesson 4
Implement Constructors in Local Classes 85Exercise 5: Create and Use Constructors 89
Lesson 5
Implementing Class Constructors in Local Classes 96Exercise 6: Create and Use Static Constructors 99
UNIT OBJECTIVES
● Define local classes● Define attributes
● Create methods
● Create objects
● Handle objects
● Call instance methods
● Call static methods
●
Call functional methods
© Copyright . All rights reserved. 37
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 50/505
● Access public attributes
● Create and Use Constructors
● Create and use static constructors
Unit 2: Fundamental Object-Oriented Syntax
38 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 51/505
Unit 2Lesson 1
37Creating Local Classes
LESSON OVERVIEWThis lesson gives you an overview on the concept of classes, attributes, and methods that arethe fundamental object-oriented syntax elements.
This is one of the most comprehensive lessons. It introduces many new concepts and syntaxelements in quick succession. It is very important that you take one small step at a time.
We highly recommend running all demonstrations in the system. Otherwise, the participants
will not be able to complete the exercises.The best approach for you is to create an empty program. First, define an empty local class inthe program and then build each step in it.
However, remember to emphasize that the example you are implementing relates to thegraphics and the presentation in the lesson. In addition, emphasize that the example differsfrom the program that the participants will use in the accompanying exercises.
This lesson is the key to understand all further lessons about object-oriented programming inABAP Objects. Make sure that there are no unanswered questions.
Business ExampleAs a developer, you need to implement classes, objects, and associations of your model inABAP Objects.
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Define local classes
● Define attributes
● Create methods
© Copyright . All rights reserved. 39
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 52/505
Definition of Local Classes
Figure 31: An Example of a Class
The concept of classes is the foundation for all object-oriented programming. A class canhave either a public access or a private access. You can access public components, such asmethods and events from outside a class. However, you cannot access private components,such as data types and attributes from outside a class.
Defining Classes
Figure 32: Defining Classes
You can define the characteristics of a class as follows:● A class is a set of objects that have the same structure and the same behavior.
● A class is like a blueprint based on which all objects in that class are created.
● All components of the class, such as attributes, methods, events, constants, types, andimplemented interfaces are defined in the definition part. You can only implementmethods in the implementation part.
Unit 2: Fundamental Object-Oriented Syntax
4 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 53/505
● The class statement cannot be nested, that is, you cannot define a class within a class.
Note:You can define local auxiliary classes for global classes.
Demonstration: How to Create Objects
To demonstrate how to create objects, implement suitable parts of programSAPBC401_BAS_D2.
Declaration of Attributes
Figure 33: An Example of Attributes
Attributes contain the data that the objects of a class store.
Class attributes can be one of following types:● Elementary
● Structured
● Table-type
Attributes can consist of data types (local or global) or reference types.
Following are the examples of attributes for the class LCL_VEHICLE:
Attributes Description
MAKE Vehicle make
MODEL Type of model
SER_NO Serial number
COLOR Color
Lesson: Creating Local Classes
© Copyright . All rights reserved. 41
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 54/505
Attributes Description
MAX_SEATS Number of seats
R_MOTOR Reference to class LCL_MOTOR
Definition of Attributes, Types, and Constants
Figure 34: Definition of Attributes, Types, and Constants
In DATA statements in classes, you can only use the TYPE addition to refer to data types.
The LIKE addition is only allowed for local data objects or SY fields (for example, SY-DATE,SY-UNAME, and so on).
The READ-ONLY addition means that a public attribute that was declared with DATA can beread from outside. However, the attribute can only be changed by methods in the same class.Currently, you can only use the READ-ONLY addition in the public visibility section (PUBLICSECTION) of a class declaration or in an interface definition.
With TYPE REF TO, you can type an attribute as a reference. This will be discussed in moredetail later.
The statement CONSTANTS is used within the class definition to define data objects thathave a constant value.
If you use the statement TYPES within the class definition, you declare a local type that isrelated especially to this class – for example, a type to be used for one or more attributes.
Unit 2: Fundamental Object-Oriented Syntax
42 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 55/505
Visibility of Attributes
Figure 35: Visibility Sections of Attributes
Visibility can be of the following types:● Private visibility
You can protect attributes against access from outside by characterizing them as privateattributes. You cannot address the private components of the class directly from outside.They are not visible to the outside user.
Note:The friendship concept is an exception to this rule.
● Public visibility
Attributes that an outside user can access directly are public attributes. In a similar way,the constants and types defined by a class can be either private, only to be used inside theclass, or public – accessible from outside the class. The public components of a class aresometimes collectively known as the interface of the class.
Using the private visibility section is also known as information hiding or encapsulation. Inpart, this is to protect the user of a class. Assume that you change the private components ofa class at some point, with its interface remaining the same. All external users can only accesstheir components through the interface of the class, and therefore, can continue to work withthe class as usual after the change. The user does not notice the change. Only the internalimplementation changes.
Conversely, if the public components of a class were incompatibly changed, every outsideuser would have to take these changes into account. You should therefore use publicattributes sparingly, or avoid making subsequent incompatible changes to the publiccomponents of your class (es) altogether.
Lesson: Creating Local Classes
© Copyright . All rights reserved. 43
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 56/505
Accessing Private Attributes
Figure 36: Accessing Private Attributes
You define private attributes in the PRIVATE SECTION of a class and public attributes in thePUBLIC SECTION.
It is syntactically impossible to access private attributes directly from outside. However, thisis possible using public methods that output or change the attributes.
The marginally higher runtime requirement (method calls in comparison with direct valueassignment) is taken into account to satisfy the encapsulation concept.
The signature of a public method clearly establishes which values must or can be transferred,and what types are to be assigned to the public methods. This relieves the outside user of allresponsibilities. The method itself is only responsible for ensuring that all private attributesare dealt consistently.
For example, imagine that the MAKE and MODEL attributes are public.
The risk would be too large, since a user might forget to supply one of the two attributes orspecify two inconsistent attributes. Instead, you could use a public method SET_TYPE toensure that values are specified for both the attributes. A strict syntax check governs methodcalls to check that all obligatory parameters are transferred. It would even be possible for themethod itself to perform a consistency check (to see if a certain vehicle make produces thechosen model), and to raise an exception if an error occurs.
To save runtime, individual attributes are sometimes defined in the public visibility section;however, they must then be given READ-ONLY addition.
Unit 2: Fundamental Object-Oriented Syntax
44 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 57/505
Static Attributes and Instance Attributes
Figure 37: Comparison of Instance Attributes with Static Attributes
Attributes are of the following types:● Instance attributes
Instance attributes exist once per object, that is, once per runtime instance of the class.You define instance attributes with the syntax element DATA.
● Static attributes
Static attributes exist once for each class and are visible for all runtime instances in thatclass. You define static attributes with the syntax element CLASS-DATA.
Static attributes usually contain the following information that applies to all instances:- Types and constants
- Central application data buffers
- Administrative information, such as the instance counter
Technical literature often refers to static attributes as class attributes (compare to theCLASS-DATA syntax element). In ABAP Objects, the official term is static attribute, as in C++and Java.
Lesson: Creating Local Classes
© Copyright . All rights reserved. 45
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 58/505
Instance Attributes and Static Attributes in the Program Context
Figure 38: Instance Attributes and Static Attributes in the Program Context
The figure shows an example of how the static attribute N_O_VEHICLES is related to the otherprogram elements in the memory. It exists only once in the loaded class regardless of thenumber of instances of LCL_VEHICLE. Therefore, you can say that instances share theircommon attributes.
Caution:Here, an integer data object is defined in order to count the instances. It is not
possible to find out the number of created instances from the system.
Demonstration: How to Define Attributes
To demonstrate how to define attributes, implement suitable parts of programSAPBC401_BAS_D1.
Unit 2: Fundamental Object-Oriented Syntax
46 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 59/505
Implementation of Methods
Figure 39: Syntax for Methods
The method characteristics are as follows:
● Methods are internal procedures in classes that determine the behavior of the objects.
They can access all attributes in their class and therefore, they can change the state ofother elements.
● Methods have a signature (interface parameters and exceptions) that enables them toreceive values when they are called and pass values back to the calling program.
● Methods can have any number of IMPORTING, EXPORTING, and CHANGING parameters.All parameters can be passed by value or reference.
Method Signature
You define a method return value using the RETURN parameter. You must always transfer theparameter as a value. In this case, you cannot define the EXPORTING and CHANGINGparameters. You can also use the RETURNING parameter to define functional methods.
You can define all input parameters (IMPORTING and CHANGING parameters) as optionalparameters in the declaration using the OPTIONAL or DEFAULT additions. You do notnecessarily need to transfer these parameters when you call the object. If you use theOPTIONAL addition, the parameter initializes according to type, while the DEFAULT additionallows you to enter a start value.
Like function modules, methods also support the return value SY-SUBRC, but only if youdefine the signature exceptions with the use of EXCEPTIONS. As of SAP Web AS 6.10, you canuse the RAISING addition in place of EXCEPTIONS to propagate class-based exceptions. Thecaller then handles these class-based exceptions without evaluating the SY-SUBRC return
value.
Lesson: Creating Local Classes
© Copyright . All rights reserved. 47
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 60/505
Note:Do not use both concepts together in one program.
Visibility of Methods
Figure 40: Visibility Sections of Methods
You assign a visibility section for methods. This determines whether the methods are calledfrom outside the class or only from within the class. Thus, private methods only serve thepurpose of internal modularization.
Accessing Private Methods
Figure 41: Accessing Private Methods
Unit 2: Fundamental Object-Oriented Syntax
48 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 61/505
You define private methods in the PRIVATE SECTION of a class. You define public attributesin the PUBLIC SECTION of a class.
It is not possible to directly access private methods from outside. However, a private methodcan be called by a public method.
In the example, INIT_TYPE is a private method that is called by the public method SET_TYPE.The instruction to initialize the attributes could exist in other contexts as well; therefore, thedefinition of this private “auxiliary method” is useful.
Note:This is an introductory example. Later, you will learn more programmingtechniques for evaluating formal parameters.
In a class, attribute names, method names, event names, constant names, type names, andalias names all share the same namespace. As with subroutines and function modules, thereis an additional local namespace within methods. This means that local declarations override
those for the whole class.
Static Methods and Instance Methods
Figure 42: Comparison of Instance Methods and Static Methods
Methods are categorized as follows:● Instance methods
You can define instance methods using the syntax keyword METHODS.
You can access both static and instance components from instance methods
● Static methods
You can define static methods using the syntax keyword CLASS-METHODS.
You define the static methods at class level. The restriction that you can access only staticcomponents applies in the implementation part. This means that static methods do not
need instances and they can be accessed directly through the class.
Lesson: Creating Local Classes
© Copyright . All rights reserved. 49
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 62/505
In the example, you can only access the static attribute N_O_VEHICLES within the staticmethod GET_N_O_VEHICLES. All other attributes of the class are instance attributes and canonly appear within instance methods.
Technical literature often refers to static methods as “class methods” (compare with theCLASS-METHODS syntax element). In ABAP Objects, the official term is static method, as in
C++ and Java.
Demonstration: How to Create Methods
To demonstrate how to create methods, implement suitable parts of programSAPBC401_BAS_D1.
Comparison of UML Class Diagram with Implementation
Figure 43: Visibility Sections and UML Notation
A UML (Unified Modeling Language) class diagram first lists the class name and then classattributes and methods below it.
The visibility of components in a class is shown in a UML using the following characters:●
A plus sign (+) indicates public components● A minus sign (–) indicates private components
● An underscore sign (_) indicates static components
Alternatively, the terms “public” and “private” can prefix a method.
A UML also allows manufacturers of modeling tools to create their own symbols for visibility.Representation of visibility characteristics is optional and is normally used only for modelsthat are close to implementation.
The method signature is represented as follows (optional):● The input and output parameters and the parameters to be changed are shown in
parentheses after the method name. The types are always specified after a colon.
Unit 2: Fundamental Object-Oriented Syntax
5 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 63/505
● The method name and the parentheses for a function method, are followed by the eventparameter, separated by a colon.
Your demonstration program should now resemble the executable programSAPBC401_BAS_D1.
Lesson: Creating Local Classes
© Copyright . All rights reserved. 51
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 64/505
Unit 2: Fundamental Object-Oriented Syntax
52 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 65/505
Unit 2Exercise 2
49Create Local Classes
Business Example
You are a developer for an airline corporation that owns several airline carriers. Start todevelop an object-oriented program that can manage the airline carriers and their airlines. Forthis reason, you must be able to define classes, attributes, and methods.
Create a new program to declare and implement classes and to define private instanceattributes and public instance method.
1. Create an executable program without a TOP include [suggested name:ZBC401_##_MAIN (where ## is your two-digit group number)].
Declare and implement a class for airplanes.
1. Within your program, declare the local class LCL_AIRPLANE.
2. Define the two private instance attributes MV_NAME (name of airplane), data typeSTRING mv_planetype (type of airplane), data type SAPLANE-PLANETYPE, and theprivate static attribute
MV_N_O_AIRPLANES (instance counter), data type I.
3. Define the public instance method SET_ATTRIBUTES for setting the private instanceattributes.
Your signature should consist of two suitable import parameters that are defined ascompatible with the two attributes.
Implement the method in such a way that the two instance attributes are set.
4. Define the public instance method DISPLAY_ATTRIBUTES for displaying the privateinstance attributes.
Implement the method in such a way that the values of the two instance attributes areoutput as an ABAP list. You can also output icons if the ICON type group is loaded.
Hint:To do this, use the statement TYPE-POOLS icon.
Note:In order to adhere to the delegation principle, the reading of the attributevalues and their output should not be implemented in the same method.However, do it here anyway because of time constraints.
© Copyright . All rights reserved. 53
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 66/505
5. Define the public static method DISPLAY_N_O_AIRPLANES to display the private staticattribute.
Implement the method in such a way that the value of the static attributes is output in theABAP list.
Note:So far, your class does not have a mechanism to ensure that the instancecounter is increased each time an object is created. It is up to you to decide ifyou want to leave this out for now, or if you want to temporarily control theincrement using the SET_ATTRIBUTES method.
6. In order to improve the list output, arrange the output in two columns, one for thedescriptive text and the other for the attribute values.
Hint:
Use addition of the WRITE statement to place the output at a given column.
To make later adjustments easier, do not use a literal for the number. Definethe private constant C_POS_1 instead.
Unit 2: Fundamental Object-Oriented Syntax
54 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 67/505
Unit 2Solution 2
51Create Local Classes
Business Example
You are a developer for an airline corporation that owns several airline carriers. Start todevelop an object-oriented program that can manage the airline carriers and their airlines. Forthis reason, you must be able to define classes, attributes, and methods.
Create a new program to declare and implement classes and to define private instanceattributes and public instance method.
1. Create an executable program without a TOP include [suggested name:ZBC401_##_MAIN (where ## is your two-digit group number)].
Declare and implement a class for airplanes.
1. Within your program, declare the local class LCL_AIRPLANE.
a) See the source code extract from the model solution.
2. Define the two private instance attributes MV_NAME (name of airplane), data typeSTRING mv_planetype (type of airplane), data type SAPLANE-PLANETYPE, and theprivate static attribute
MV_N_O_AIRPLANES (instance counter), data type I.a) See the source code extract from the model solution.
3. Define the public instance method SET_ATTRIBUTES for setting the private instanceattributes.
Your signature should consist of two suitable import parameters that are defined ascompatible with the two attributes.
Implement the method in such a way that the two instance attributes are set.
a) See the source code extract from the model solution.
4. Define the public instance method DISPLAY_ATTRIBUTES for displaying the private
instance attributes.Implement the method in such a way that the values of the two instance attributes areoutput as an ABAP list. You can also output icons if the ICON type group is loaded.
Hint:To do this, use the statement TYPE-POOLS icon.
© Copyright . All rights reserved. 55
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 68/505
Note:In order to adhere to the delegation principle, the reading of the attributevalues and their output should not be implemented in the same method.However, do it here anyway because of time constraints.
a) See the source code extract from the model solution.
5. Define the public static method DISPLAY_N_O_AIRPLANES to display the private staticattribute.
Implement the method in such a way that the value of the static attributes is output in theABAP list.
Note:So far, your class does not have a mechanism to ensure that the instancecounter is increased each time an object is created. It is up to you to decide ifyou want to leave this out for now, or if you want to temporarily control theincrement using the SET_ATTRIBUTES method.
a) See the source code extract from the model solution.
6. In order to improve the list output, arrange the output in two columns, one for thedescriptive text and the other for the attribute values.
Hint:Use addition of the WRITE statement to place the output at a given column.
To make later adjustments easier, do not use a literal for the number. Definethe private constant C_POS_1 instead.
a) See the source code extract from the model solution.
Following is the source code extract:
SAPBC401_BAS_S1
REPORT sapbc401_bas_s1.
TYPE-POOLS icon.
*--------------------------------------------------------*
* CLASS lcl_airplane DEFINITION **--------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
METHODS:
set_attributes
IMPORTING
Unit 2: Fundamental Object-Oriented Syntax
56 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 69/505
iv_name TYPE string iv_planetype TYPE saplane-planetype,
display_attributes.
CLASS-METHODS:
display_n_o_airplanes. PROTECTED SECTION.
PRIVATE SECTION.
CONSTANTS:
c_pos_1 TYPE i VALUE 30.
DATA:
mv_name TYPE string, mv_planetype TYPE saplane-planetype.
CLASS-DATA:
gv_n_o_airplanes TYPE i.
ENDCLASS. "lcl_airplane DEFINITION
*---------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION * *---------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD set_attributes.
mv_name = iv_name. mv_planetype = iv_planetype.
* doesn't make sense so much – * only in order to get an effect * after calling display_n_o_airplanes:
gv_n_o_airplanes = gv_n_o_airplanes + 1.
ENDMETHOD. "set_attributes
METHOD display_attributes.
DATA: lv_weight TYPE saplane-weight, lv_cap TYPE saplane-tankcap.
WRITE:
/ icon_ws_plane AS ICON, / 'Name of Airplane'(001), AT c_pos_1 mv_name, / 'Type of Airplane:'(002), AT c_pos_1 mv_planetype.
ENDMETHOD. "display_attributes
Lesson: Creating Local Classes
© Copyright . All rights reserved. 57
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 70/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 71/505
LESSON SUMMARYYou should now be able to:
● Define local classes
● Define attributes
● Create methods
Lesson: Creating Local Classes
© Copyright . All rights reserved. 59
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 72/505
Unit 2Lesson 2
56Creating and Working with Objects
LESSON OVERVIEWThis lesson explains the concept of creating and handling objects.
Business Example
As a developer, you must create multiple instances of the airplane class. For this reason, yourequire the following knowledge:
● An understanding of objects
● An understanding of how to handle objects
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Create objects
● Handle objects
Objects as Instances of Classes
Figure 44: Overview of Instances of Classes
You can use classes to write complete applications by using just static components. However,the reasoning behind object-oriented programming is to create and work with runtimeinstances of classes.
A class contains the generic description of an object and describes all characteristics that allobjects of the class have in common. During the program runtime, you use the class to creatediscrete objects (instances) in the memory. This process is called instantiation. When theclass is accessed for the first time, it is loaded into the memory.
To create objects, use the statement CREATE OBJECT ref_ name. You can only create andaddress objects using reference variables.
6 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 73/505
It is irrelevant as to which values may be written into which attributes. Technically, the objecthas an ID (in this case, 5), which is not accessible. For example, create an instance of classLCL_VEHICLE a vehicle object. The private attributes still contain the technical initial values.
Definition of Reference Variables
Figure 45: Definition of Reference Variables
To define a reference variable, use the DATA go_vehicle1 TYPE REF TO lcl_vehicle, which istyped as a pointer to objects of type lcl_vehicle. The null reference is the technical initial valueof a reference variable. The pointer is pointing to nothing.
Creating Objects
Figure 46: Creating Objects
The statement CREATE OBJECT creates an object in the memory. Its attribute values areinitial or assigned according to the VALUE specification.
Lesson: Creating and Working with Objects
© Copyright . All rights reserved. 61
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 74/505
Reference Semantics of Object References
Figure 47: Reference Semantics of Object References
Experienced participants may suggest using field symbols for this. If this happens, it is a goodopportunity to clarify the principal differences again.
It is important for you to complete and discuss the exercises at the relevant stages of thislesson. These exercises are arranged sequentially, such that each prepares the way for thenext. This can be especially motivating if you demonstrate the exercises for the participantsor have them perform the exercises. The topics covered here and the successful completionof the exercises is very important for the rest of the course.
Reference variables can also be assigned to each other.
The figure illustrates an example where after the MOVE statement, GO_VEHICLE1 andGO_VEHICLE2 point to the same object.
How To Create ObjectsTo demonstrate how to create objects by implementing suitable parts of programSAPBC401_BAS_D2.
Unit 2: Fundamental Object-Oriented Syntax
62 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 75/505
The Garbage Collector
Figure 48: The Garbage Collector
Do not spend more than a minute discussing the Garbage Collector. Application developerscannot influence it. Developers also do not have to work any differently depending onwhether the Garbage Collector is running. Some experienced participants refuse to acceptthat they can no longer access objects whose addresses have been lost.
Caution:
The query for IS BOUND is although possible here, it makes a difference fordata references. If you encounter a question on this, the answer is that in thecase of object references, you can work with both.
Independent references are references that have not been defined within a class. TheGarbage Collector is a system routine that starts automatically whenever the runtime systemdoes not have more important tasks to carry out.
In this example, the reference to object (2) LCL_OBJECT is initialized. Thereafter, there is noreference point to this object. Therefore, the Garbage Collector deletes the object without
reference. So, since there is no reference point to object (4) LCL_OBJECT, it is also deleted.You can use the logical query IF go_obj IS INITIAL to determine whether r_obj contains thenull reference or it does not point to any object.
Lesson: Creating and Working with Objects
© Copyright . All rights reserved. 63
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 76/505
Multiple Instances
Figure 49: Reference Administration with Multiple Instantiation
The slide displaying the component selector “ ->” is discussed later.
If you want to keep several objects from the same class in your program, you can define aninternal table, contains one column with the object references for this class. You canadminister these objects in the internal table with the usual statements for internal tablessuch as APPEND, READ, or LOOP.
Example of Aggregation
Figure 50: Example of Aggregation
Unit 2: Fundamental Object-Oriented Syntax
64 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 77/505
During an aggregation, the WHEEL objects must be existing on their own, in other words,independent of the vehicle. Independent references must, however, still exist to them. This isindicated by the green arrows pointing to the WHEEL objects.
Your demonstration program should now resemble the executable programSAPBC401_BAS_D2.
Here, the next exercise would be suitable for the AIRPLANE objects referenced in the internaltable.
The objects in the class LCL_WHEEL have their own identity. You can create objectsregardless of the existence of an object in the class LCL_VEHICLE. References are transferredto objects in class LCL_VEHICLE to create the desired association.
Lesson: Creating and Working with Objects
© Copyright . All rights reserved. 65
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 78/505
Unit 2: Fundamental Object-Oriented Syntax
66 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 79/505
Unit 2Exercise 3
61Create Objects
Business Example
As a developer, create instances of your airplane class and ensure that the references to theobjects are not lost.
Template:
SAPBC401_BAS_S1
Solution:
SAPBC401_BAS_S2
Task 1
Define a reference variable and then create airplane objects.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise.
Define a reference variable for the instances of your class LCL_AIRPLANE.
2. Define an internal table for buffering references to instances of the class LCL_AIRPLANE.
Task 2
Create airplane objects.
1. Create several instances of the local class LCL_AIRPLANE and buffer their references intothe internal table.
Create airplane objects.
2. Observe the execution of the program in the ABAP Debugger.
© Copyright . All rights reserved. 67
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 80/505
Unit 2Solution 3
62Create Objects
Business Example
As a developer, create instances of your airplane class and ensure that the references to theobjects are not lost.
Template:
SAPBC401_BAS_S1
Solution:
SAPBC401_BAS_S2
Task 1
Define a reference variable and then create airplane objects.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise.
Define a reference variable for the instances of your class LCL_AIRPLANE.
a) See the source code extract from the model solution.
2. Define an internal table for buffering references to instances of the class LCL_AIRPLANE.
a) See the source code extract from the model solution.
Task 2
Create airplane objects.
1. Create several instances of the local class LCL_AIRPLANE and buffer their references intothe internal table.
Create airplane objects.
a) See the source code extract from the model solution.
2. Observe the execution of the program in the ABAP Debugger.a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
REPORT sapbc401_bas_s2.
TYPE-POOLS icon.
*---------------------------------------------------------------* CLASS lcl_airplane DEFINITION **---------------------------------------------------------------*CLASS lcl_airplane DEFINITION.
68 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 81/505
...
ENDCLASS. "lcl_airplane DEFINITION
*---------------------------------------------------------------** CLASS lcl_airplane IMPLEMENTATION*
*---------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION.
...
ENDCLASS. "lcl_airplane IMPLEMENTATION
DATA: go_airplane TYPE REF TO lcl_airplane.
DATA: gt_airplanes TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
******************* CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
Lesson: Creating and Working with Objects
© Copyright . All rights reserved. 69
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 82/505
LESSON SUMMARYYou should now be able to:
● Create objects
● Handle objects
Unit 2: Fundamental Object-Oriented Syntax
7 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 83/505
Unit 2Lesson 3
65Accessing Methods and Attributes
LESSON OVERVIEWThis lesson explains the process of accessing methods and attributes.
Business Example
As a developer, you need to explain the various ways of accessing methods and attributes of aclass. For this reason, you require the following knowledge:
● An understanding of methods
● An understanding of attributes
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Call instance methods
● Call static methods
● Call functional methods
● Access public attributes
Call of Instance Methods
Figure 51: Calling Methods
© Copyright . All rights reserved. 71
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 84/505
You can use classes to write complete applications by using only static components.However, the reasoning behind object-oriented programming is to create and work withruntime instances of classes.
A class contains the generic description of an object and describes all the characteristics thatall objects of the class have in common. During program runtime, you use the class to create
discrete objects (instances) in the memory. This process is called instantiation. When theclass is accessed for the first time, it is loaded into the memory.
To create objects, use the statement CREATE OBJECT ref_ name. You can only create andaddress them using reference variables.
It is irrelevant as to which values may be written into which attributes. Technically, the objecthas an ID (in this case, 5), which is not accessible. For example, create an instance of classLCL_VEHICLE a vehicle object. The private attributes still contain the technical initial values.
Syntax for Calling Instance Methods
Figure 52: Calling Instance Methods – Syntax
The shorter syntax was introduced to make ABAP Objects syntax resemble C++ and Javasyntax more closely. However, since participants will also have to maintain the older sourcecode, they need to know the explicit syntax as well.
CALL METHOD ref->method_name is the syntax used to call Instance methods. When callingan instance method from within another instance method, you can omit the instance nameref. The method is automatically executed for the current object.
A shorter syntax is also supported as of in SAP Web AS 6.10. In this version, omit CALLMETHOD and list the parameters in parentheses. There must be no space before theparentheses, but there must be at least one space after the parentheses. When you call amethod that has only one import parameter, you can specify the actual parameter in theparentheses without any other additions. When you call a method that only has importparameters, you can omit the EXPORTING addition.
Unit 2: Fundamental Object-Oriented Syntax
72 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 85/505
Demonstration: How to Call Instance Methods
To demonstrate how to call instance methods using suitable parts of programSAPBC401_BAS_D3.
Call of Static Methods
Figure 53: Calling Static Methods – Syntax
Please refer to the concept about Call of Functional Methods for more details. Perform theexercise for the method calls and the sub-exercise on the functional methods separately,else the participants may get confused and mix up all of the techniques.
The RECEIVING, IMPORTING, and CHANGING parameters are mutually exclusive. Otherwise,the same rules apply here as they do for calling a function module.
Use CALLMETHOD classname=>method_name to call static methods (also referred to asclass methods).
Like static attributes, static methods are addressed with their class name, since they do not
need instances.As with instance methods, when you are calling a static method from within the class, you canomit the class name. Otherwise, the same rules apply here as for calling an instance method.
Demonstration: How to Call Static Methods
To demonstrate how to call static methods using suitable parts of programSAPBC401_BAS_D3.
Lesson: Accessing Methods and Attributes
© Copyright . All rights reserved. 73
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 86/505
Call of Functional Methods
Figure 54: Functional Methods
Functional method calls are sometimes confused with the short forms of other method calls.The former are possible from the beginning that is, as of SAP R/34.6A. The latter are onlypossible as of SAP Web AS 6.10.
The exercise step that handles functional methods should be performed on its own and as aseparate step.
You describe methods that have a RETURNING parameter as functional methods. This meansthat they can have neither an EXPORTING nor a CHANGING parameter. You have to pass theRETURNING parameter using the VALUE addition, that is, pass by value.
You can call functional methods directly within the following expressions:● Logical expressions: IF, ELSEIF, WHILE, CHECK, WAIT
● Arithmetic expressions and bit expressions: COMPUTE
● Case conditions: CASE, WHEN
● Sources of values as a local copy: MOVE
● Search clauses for internal tables, assuming that the operand is not a component of thetable row: LOOP AT ... WHERE
Demonstration: How to Call Static Methods
To demonstrate how to call static methods using suitable parts of programSAPBC401_BAS_S3.
Unit 2: Fundamental Object-Oriented Syntax
74 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 87/505
Functional Methods – Examples
Figure 55: Functional Methods – Examples
In the first part of the example, two calls of functional instance methods represent the twoaddends of an addition.
The second example shows the call of a functional static method in short form. The NUMBERdata object is the actual parameter for the RETURNING parameter of the method. Thedetailed syntax is as follows:
DATA gv_number TYPE i.
...
CALL METHOD lcl_vehicle=>get_n_o_vehicles
RECEIVING rv_count = gv_number.
Lesson: Accessing Methods and Attributes
© Copyright . All rights reserved. 75
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 88/505
Access to Public Attributes
Figure 56: Accessing Public Attributes
Your demonstration program should now resemble the executable programSAPBC401_BAS_D3.SAPBC401_BAS_D3.
You access public attributes from outside the class in the same way as method calls. You canaccess static attributes using classname=>static_attribute . Access instance attributeswith ref->instance_attribute .
Demonstration: How to Access Methods and Attributes
To demonstrate how to access methods and attributes using suitable parts of programSAPBC401_BAS_D3.
Unit 2: Fundamental Object-Oriented Syntax
76 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 89/505
Unit 2Exercise 4
71Call Methods
Business Example
As a developer, you need to fill the attributes of the "empty" airplane objects with suitablevalues.
Template:
SAPBC401_BAS_S2
Solution:
SAPBC401_BAS_S3
Task 1
Call the methods of your class.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise.
Call the static method DISPLAY_N_O_AIRPLANES twice; once before and once after theinstantiations.
2. Use the SET_ATTRIBUTES method to set the attributes for all objects that have alreadybeen created. Choose a unique name for the airplanes. When assigning airplane types, usethe information in the SAPLANE table as a guide (for example, ‘747-400’).
3. Display the attribute values for all the airplanes in a loop in the ABAP list using theDISPLAY_ATTRIBUTES method.
Task 2
Add a functional method to your class.
1. In your class, define the public static functional method GET_N_O_AIRPLANES. Thesignature must only consist of the result parameter RV_COUNT, which must be an integer.
2. Call this method in the main program and output the value in the ABAP list.
c401_bas_s3.
TYPE-POOLS icon.
*------------------------------------------------------------------** CLASS lcl_airplane DEFINITION
**------------------------------------------------------------------*CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
METHODS:
© Copyright . All rights reserved. 77
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 90/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 91/505
METHOD get_n_o_airplanes.
rv_count = gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes
ENDCLASS. "lcl_airplane IMPLEMENTATION
DATA: go_airplane TYPE REF TO lcl_airplane, gt_airplanes TYPE TABLE OF REF TO lcl_airplane,
gv_count TYPE i.
START-OF-SELECTION.*******************
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
go_airplane->set_attributes( iv_name = 'LH Berlin' iv_planetype = 'A321' ).
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
go_airplane->set_attributes( iv_name = 'AA New York' iv_planetype = '747-400' ).
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
go_airplane->set_attributes( iv_name = 'US Hercules' iv_planetype = '747-200F' ).
LOOP AT gt_airplanes INTO go_airplane. go_airplane->display_attributes( ). ENDLOOP.
* long syntax for functional call:* CALL METHOD lcl_airplane=>get_n_o_airplanes* RECEIVING* rv_count = gv_count.
* a little bit shorter:* lcl_airplane=>get_n_o_airplanes( RECEIVING rv_count = gv_count).
* the shortest syntax for functional call: gv_count = lcl_airplane=>get_n_o_airplanes( ).
SKIP 2. WRITE: / 'Number of airplanes'(ca1), gv_count.
Lesson: Accessing Methods and Attributes
© Copyright . All rights reserved. 79
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 92/505
Unit 2Solution 4
74Call Methods
Business Example
As a developer, you need to fill the attributes of the "empty" airplane objects with suitablevalues.
Template:
SAPBC401_BAS_S2
Solution:
SAPBC401_BAS_S3
Task 1
Call the methods of your class.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise.
Call the static method DISPLAY_N_O_AIRPLANES twice; once before and once after theinstantiations.
a) See the source code extract from the model solution.
Caution:For reasons explained in the exercise Create UML Diagrams, you may notnotice any effects at the moment.
2. Use the SET_ATTRIBUTES method to set the attributes for all objects that have alreadybeen created. Choose a unique name for the airplanes. When assigning airplane types, usethe information in the SAPLANE table as a guide (for example, ‘747-400’).
a) See the source code extract from the model solution.
3. Display the attribute values for all the airplanes in a loop in the ABAP list using the
DISPLAY_ATTRIBUTES method.a) See the source code extract from the model solution.
Task 2
Add a functional method to your class.
1. In your class, define the public static functional method GET_N_O_AIRPLANES. Thesignature must only consist of the result parameter RV_COUNT, which must be an integer.
a) See the source code extract from the model solution.
2. Call this method in the main program and output the value in the ABAP list.
8 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 93/505
a) See the source code extract from the model solution.
c401_bas_s3.
TYPE-POOLS icon.
*------------------------------------------------------------------** CLASS lcl_airplane DEFINITION*
*------------------------------------------------------------------*CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
METHODS: set_attributes IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype,
display_attributes. CLASS-METHODS: display_n_o_airplanes,
get_n_o_airplanes RETURNING value(rv_count) TYPE i.
PROTECTED SECTION.
PRIVATE SECTION.
CONSTANTS:
c_pos_1 TYPE i VALUE 30.
DATA: mv_name TYPE string, mv_planetype TYPE saplane-planetype.
CLASS-DATA: gv_n_o_airplanes TYPE i.ENDCLASS. "lcl_airplane DEFINITION
*------------------------------------------------------------------** CLASS lcl_airplane IMPLEMENTATION
**------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD set_attributes.
mv_name = iv_name. mv_planetype = iv_planetype.
* doesn't make sense so much -* only in order to get an effect* after calling display_n_o_airplanes: gv_n_o_airplanes = gv_n_o_airplanes + 1.
ENDMETHOD. "set_attributes
METHOD display_attributes. DATA: lv_weight TYPE saplane-weight,
Lesson: Accessing Methods and Attributes
© Copyright . All rights reserved. 81
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 94/505
lv_cap TYPE saplane-tankcap.
WRITE: / icon_ws_plane AS ICON, / 'Name of Airplane'(001) , AT c_pos_1 mv_name, / 'Type of Airplane:'(002), AT c_pos_1 mv_planetype.
ENDMETHOD. "display_attributes METHOD display_n_o_airplanes. SKIP. WRITE: / 'Number of airplanes:'(ca1), AT c_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD. "display_n_o_airplanes
METHOD get_n_o_airplanes.
rv_count = gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes
ENDCLASS. "lcl_airplane IMPLEMENTATION
DATA: go_airplane TYPE REF TO lcl_airplane, gt_airplanes TYPE TABLE OF REF TO lcl_airplane,
gv_count TYPE i.
START-OF-SELECTION.*******************
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
go_airplane->set_attributes( iv_name = 'LH Berlin' iv_planetype = 'A321' ).
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
go_airplane->set_attributes( iv_name = 'AA New York' iv_planetype = '747-400' ).
CREATE OBJECT go_airplane. APPEND go_airplane TO gt_airplanes.
go_airplane->set_attributes( iv_name = 'US Hercules' iv_planetype = '747-200F' ).
LOOP AT gt_airplanes INTO go_airplane. go_airplane->display_attributes( ).
ENDLOOP.* long syntax for functional call:
Unit 2: Fundamental Object-Oriented Syntax
82 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 95/505
* CALL METHOD lcl_airplane=>get_n_o_airplanes* RECEIVING* rv_count = gv_count.
* a little bit shorter:* lcl_airplane=>get_n_o_airplanes( RECEIVING rv_count = gv_count).
* the shortest syntax for functional call: gv_count = lcl_airplane=>get_n_o_airplanes( ).
SKIP 2. WRITE: / 'Number of airplanes'(ca1), gv_count.
Lesson: Accessing Methods and Attributes
© Copyright . All rights reserved. 83
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 96/505
LESSON SUMMARYYou should now be able to:
● Call instance methods
● Call static methods
● Call functional methods
● Access public attributes
Unit 2: Fundamental Object-Oriented Syntax
84 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 97/505
Unit 2Lesson 4
79Implement Constructors in Local Classes
LESSON OVERVIEWThis lesson explains the implementation of constructor methods in local classes.
Business Example
As a developer, explain the creation and use of static constructors for airplane class. For thisreason, you require the following knowledge:
● An understanding of static constructors
● An understanding of using static constructors
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Create and Use Constructors
Constructor
Figure 57: (Instance) Constructor
There are two types of methods in ABAP Objects. They are not called explicitly with CALLMETHOD (or the relevant short form), rather they are called implicitly. Constructors are thefirst type of method.
© Copyright . All rights reserved. 85
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 98/505
Some participants who are experienced in other object-oriented languages may struggle atthis point. In some of the other object-oriented languages, the constructor concept is useddifferently from the way it is used in ABAP Objects. Try to avoid this confusion because theconcept is actually very simple.
The constructor is a special instance method in a class and is always named CONSTRUCTOR.This abbreviated term actually means the instance constructor. The constructor isautomatically called at runtime with the CREATE OBJECT statement.
When you define constructors, always consider the following points:● Each class has not more than one (instance) constructor.
● Define the constructor in the public area.
● The signature of the customer can only have importing parameters and exceptions.
● When exceptions are raised in the constructor, instances are not created, so no main
memory space is occupied.● Except for one exceptional case, you cannot call the constructor explicitly.
Note:There is no destructor in ABAP Objects, that is, there is no instance method thatyou can automatically call from the memory immediately before the object isdeleted.
The corresponding comments in the SAP Library and the menu paths outside ofthe ABAP Workbench are only contained in internal system calls.
Unfortunately, they are not dynamically hidden. If they were, you would not need to deal withthe participants’ questions. Avoid any discussion about the SAP Library and the menu paths.
Unit 2: Fundamental Object-Oriented Syntax
86 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 99/505
Constructor – Example
Figure 58: Constructor – Example
Your demonstration program should now resemble the executable programSAPBC401_BAS_D4.
After the instantiation of a class, a constructor is necessary for the following conditions:● If you must allocate resources
● If you must initialize attributes that cannot be covered by the VALUE addition to the DATAstatement
● If you must modify static attributes
● If you must send messages containing the information that a new object was created
Now you can perform the appropriate exercise for the instance constructor. The exercise forthe static constructor should be performed later.
Demonstration: How to Create and Use ConstructorsTo demonstrate how to create and use constructors, implement suitable parts of theprogram SAPBC401_BAS_D4.
Lesson: Implement Constructors in Local Classes
© Copyright . All rights reserved. 87
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 100/505
Unit 2: Fundamental Object-Oriented Syntax
88 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 101/505
Unit 2Exercise 5
83Create and Use Constructors
Business Example
Make your program more realistic. The airplane objects receive their attributes as soon asthey are created. Make sure that airplane objects can only be created with plane types storedin database table SAPLANE.
Template:
SAPBC401_BAS_S3
Solution:
SAPBC401_BAS_S4
Task 1
Define an instance constructor.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise, where ## is your two-digit group number.
Define a constructor with a suitable signature for the instances of your classLCL_AIRPLANE.
Implement it in a way that the two instance attributes are set and the instance counter
N_O_AIRPLANES is increased by one.
2. Remove the definition and implementation of method SET_ATTRIBUTES to ensure that anattribute of instance can only be set once during its creation.
Task 2
Create airplane objects.
1. Your CREATE OBJECT statements from the previous exercise should now be syntacticallyincorrect. Adapt and correct them.
2. Remove the calls of the SET_ATTRIBUTES method.
3. Follow the execution of the program in the ABAP Debugger.
Task 3
Define additional instance attributes with technical information about the airplane. Set theseattributes in your constructor by accessing database table SAPLANE. Raise an exception ifthe specified plane type is not found in the database.
1. In your class, define the private instance attributes MV_WEIGHT (data type SAPLANE-WEIGHT) and MV_TANKCAP (data type SAPLANE_TANKCAP).
© Copyright . All rights reserved. 89
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 102/505
2. Extend the definition of the instance constructor by adding a classical exception that is notclass based, WRONG_PLANETYPE.
3. Extend the implementation of the constructor. Read a single record from database tableSAPLANE for the specified plane type and set the new attributes accordingly.
Raise the exception if no data is found for the given plane type.
4. Adjust the CREATE OBJECT statements, so that you handle the exception. Only store theobject reference in your table if the creation was successful.
5. Follow the execution of the program in the ABAP Debugger. For test reasons, specify anon existing plane type to see how the exception handling works.
SAPBC401_BAS_S4
REPORT sapbc401_bas_s4. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: /Instruction/
Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> constructor IMPORTING iv_name TYPE stringiv_planetype TYPE saplane-planetype EXCEPTIONS wrong_planetype, </EmphasisContent> display_attributes. CLASS-METHODS:display_n_o_airplanes, get_n_o_airplanes RETURNING value(rv_count)TYPE i. PRIVATE SECTION. CONSTANTS: c_pos_1 TYPE i VALUE 30. DATA:mv_name TYPE string, mv_planetype TYPE saplane-planetype,/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> mv_weight TYPE saplane-weight, mv_tankcap TYPEsaplane-tankcap.</EmphasisContent> CLASS-DATA: gv_n_o_airplanes TYPEi. ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION. /Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for: <EmphasisContent> METHODconstructor. DATA: ls_planetype TYPE saplane. mv_name = iv_name.mv_planetype = iv_planetype. SELECT SINGLE * FROM saplane INTOls_planetype WHERE planetype = iv_planetype. IF sy-subrc <> 0. RAISEwrong_planetype. ELSE. mv_weight = ls_planetype-weight. mv_tankcap =ls_planetype-tankcap. gv_n_o_airplanes = gv_n_o_airplanes + 1. ENDIF.ENDMETHOD. "constructor </EmphasisContent> METHOD display_attributes.WRITE: / icon_ws_plane AS ICON, / 'Name of Airplane'(001) , AT c_pos_1mv_name, / 'Type of Airplane:'(002), AT c_pos_1 mv_planetype,/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> / 'Weight:'(003), AT c_pos_1 mv_weight LEFT-JUSTIFIED, / 'Tank capacity:'(004), AT c_pos_1 mv_tankcap LEFT-JUSTIFIED.</EmphasisContent> ENDMETHOD. "display_attributes METHOD
display_n_o_airplanes. SKIP. WRITE: / 'Number of airplanes:'(ca1), ATc_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD."display_n_o_airplanes METHOD get_n_o_airplanes. rv_count =gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes ENDCLASS."lcl_airplane IMPLEMENTATION DATA: go_airplane TYPE REF TOlcl_airplane, gt_airplanes TYPE TABLE OF REF TO lcl_airplane, gv_countTYPE i. START-OF-SELECTION. *******************lcl_airplane=>display_n_o_airplanes( ). CREATE OBJECT go_airplane/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> EXPORTING iv_name = 'LH Berlin' iv_planetype ='A321' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.</EmphasisContent> APPEND go_airplane TO gt_airplanes./Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> ENDIF.</EmphasisContent> CREATE OBJECT go_airplane/
Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> EXPORTING iv_name = 'AA New York' iv_planetype =
Unit 2: Fundamental Object-Oriented Syntax
9 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 103/505
'747-400' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.</EmphasisContent> APPEND go_airplane TO gt_airplanes./Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> ENDIF.</EmphasisContent> CREATE OBJECT go_airplane/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> EXPORTING iv_name = 'US Hercules' iv_planetype ='747-200F' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.</
EmphasisContent> APPEND go_airplane TO gt_airplanes./Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> ENDIF.</EmphasisContent> LOOP AT gt_airplanes INTOgo_airplane. go_airplane->display_attributes( ). ENDLOOP. gv_count =lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: / 'Number ofairplanes'(ca1), gv_count.
Lesson: Implement Constructors in Local Classes
© Copyright . All rights reserved. 91
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 104/505
Unit 2Solution 5
86Create and Use Constructors
Business Example
Make your program more realistic. The airplane objects receive their attributes as soon asthey are created. Make sure that airplane objects can only be created with plane types storedin database table SAPLANE.
Template:
SAPBC401_BAS_S3
Solution:
SAPBC401_BAS_S4
Task 1
Define an instance constructor.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise, where ## is your two-digit group number.
Define a constructor with a suitable signature for the instances of your classLCL_AIRPLANE.
Implement it in a way that the two instance attributes are set and the instance counter
N_O_AIRPLANES is increased by one.a) See the source code extract from the model solution.
2. Remove the definition and implementation of method SET_ATTRIBUTES to ensure that anattribute of instance can only be set once during its creation.
a) See the source code extract from the model solution.
Task 2
Create airplane objects.
1. Your CREATE OBJECT statements from the previous exercise should now be syntacticallyincorrect. Adapt and correct them.
a) See the source code extract from the model solution.
2. Remove the calls of the SET_ATTRIBUTES method.
a) See the source code extract from the model solution.
3. Follow the execution of the program in the ABAP Debugger.
a) Carry out this step in the usual manner. Additional information on the ABAP Debuggeris available in the SAP Library.
Task 3
92 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 105/505
Define additional instance attributes with technical information about the airplane. Set theseattributes in your constructor by accessing database table SAPLANE. Raise an exception ifthe specified plane type is not found in the database.
1. In your class, define the private instance attributes MV_WEIGHT (data type SAPLANE-WEIGHT) and MV_TANKCAP (data type SAPLANE_TANKCAP).
a) See the source code extract from the model solution.
2. Extend the definition of the instance constructor by adding a classical exception that is notclass based, WRONG_PLANETYPE.
a) See the source code extract from the model solution.
3. Extend the implementation of the constructor. Read a single record from database tableSAPLANE for the specified plane type and set the new attributes accordingly.
Raise the exception if no data is found for the given plane type.
a) See the source code extract from the model solution.
4. Adjust the CREATE OBJECT statements, so that you handle the exception. Only store theobject reference in your table if the creation was successful.a) See the source code extract from the model solution.
5. Follow the execution of the program in the ABAP Debugger. For test reasons, specify anon existing plane type to see how the exception handling works.
a) Carry out this step in the usual manner. Additional information on the ABAP Debuggeris available in the SAP Library.
SAPBC401_BAS_S4
REPORT sapbc401_bas_s4. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: /Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> constructor IMPORTING iv_name TYPE stringiv_planetype TYPE saplane-planetype EXCEPTIONS wrong_planetype, </EmphasisContent> display_attributes. CLASS-METHODS:display_n_o_airplanes, get_n_o_airplanes RETURNING value(rv_count)TYPE i. PRIVATE SECTION. CONSTANTS: c_pos_1 TYPE i VALUE 30. DATA:mv_name TYPE string, mv_planetype TYPE saplane-planetype,/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> mv_weight TYPE saplane-weight, mv_tankcap TYPEsaplane-tankcap.</EmphasisContent> CLASS-DATA: gv_n_o_airplanes TYPEi. ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. /Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for: <EmphasisContent> METHODconstructor. DATA: ls_planetype TYPE saplane. mv_name = iv_name.mv_planetype = iv_planetype. SELECT SINGLE * FROM saplane INTOls_planetype WHERE planetype = iv_planetype. IF sy-subrc <> 0. RAISEwrong_planetype. ELSE. mv_weight = ls_planetype-weight. mv_tankcap =ls_planetype-tankcap. gv_n_o_airplanes = gv_n_o_airplanes + 1. ENDIF.ENDMETHOD. "constructor </EmphasisContent> METHOD display_attributes.WRITE: / icon_ws_plane AS ICON, / 'Name of Airplane'(001) , AT c_pos_1mv_name, / 'Type of Airplane:'(002), AT c_pos_1 mv_planetype,/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> / 'Weight:'(003), AT c_pos_1 mv_weight LEFT-JUSTIFIED, / 'Tank capacity:'(004), AT c_pos_1 mv_tankcap LEFT-JUSTIFIED.</EmphasisContent> ENDMETHOD. "display_attributes METHOD
Lesson: Implement Constructors in Local Classes
© Copyright . All rights reserved. 93
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 106/505
display_n_o_airplanes. SKIP. WRITE: / 'Number of airplanes:'(ca1), ATc_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD."display_n_o_airplanes METHOD get_n_o_airplanes. rv_count =gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes ENDCLASS."lcl_airplane IMPLEMENTATION DATA: go_airplane TYPE REF TOlcl_airplane, gt_airplanes TYPE TABLE OF REF TO lcl_airplane, gv_countTYPE i. START-OF-SELECTION. *******************
lcl_airplane=>display_n_o_airplanes( ). CREATE OBJECT go_airplane/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> EXPORTING iv_name = 'LH Berlin' iv_planetype ='A321' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.</EmphasisContent> APPEND go_airplane TO gt_airplanes./Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> ENDIF.</EmphasisContent> CREATE OBJECT go_airplane/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> EXPORTING iv_name = 'AA New York' iv_planetype ='747-400' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.</EmphasisContent> APPEND go_airplane TO gt_airplanes./Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> ENDIF.</EmphasisContent> CREATE OBJECT go_airplane/Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:
<EmphasisContent> EXPORTING iv_name = 'US Hercules' iv_planetype ='747-200F' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.</EmphasisContent> APPEND go_airplane TO gt_airplanes./Instruction/Exercise/Result/SourceCode/Content:: Unaccounted for:<EmphasisContent> ENDIF.</EmphasisContent> LOOP AT gt_airplanes INTOgo_airplane. go_airplane->display_attributes( ). ENDLOOP. gv_count =lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: / 'Number ofairplanes'(ca1), gv_count.
Unit 2: Fundamental Object-Oriented Syntax
94 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 107/505
LESSON SUMMARYYou should now be able to:
● Create and Use Constructors
Lesson: Implement Constructors in Local Classes
© Copyright . All rights reserved. 95
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 108/505
Unit 2Lesson 5
90Implementing Class Constructors in Local
Classes
LESSON OVERVIEWThis lesson explains the creation and use of static constructors and self-reference.
Business Example
As a developer, you need to explain the creation and use of static constructors for airplaneclass. For this reason, you require the following knowledge:
● An understanding of static constructor● An understanding of self-reference
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Create and use static constructors
Static Constructor
Figure 59: Example of a Static Constructor
The exercise for the static constructor should be done here. This also has the advantage thatthe participants will finally get to grips with SQL accesses and learn that nothing changes interms of their SQL knowledge.
96 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 109/505
The static constructor is a special static method in a class and is always namedCLASS_CONSTRUCTOR. The static constructor of a class is executed only once per program.
Call the static constructor automatically before the class is first accessed.
You can access the static constructor before any of the following actions are executed forthe first time:● Creating an instance of the class (CREATE OBJECT)
● Accessing a static attribute of this class
● Calling a static method of this class
● Registering an event handler method for an event in this class
When you define static constructors, always consider the following points:● Each class has not more than one static constructor
● The static constructor must be defined in the public area
● The constructor’s signature cannot have importing parameters or exceptions● The static constructor cannot be called explicitly
Self-Reference
Figure 60: Self-Reference
You could make a careful comparison with the LOAD-OF-PROGRAM ABAP event for functiongroups.
You can address an object itself by using the predefined reference variable ME within itsinstance methods. You do not need to use the prefix me-> in such cases, but you may use it toimprove readability.
However, you require the prefix me-> when you want to show a distinction between local data
objects and instance attributes with the same name.
Lesson: Implementing Class Constructors in Local Classes
© Copyright . All rights reserved. 97
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 110/505
The case shows another important use.
When you call a foreign method, a client object is required to export a reference to itself. Then,you can use ME as an actual parameter with EXPORTING or CHANGING.
Demonstration: How to Create and Use Static Constructors
To demonstrate how to create and implement suitable parts of programSAPBC401_BAS_D5.
This is a good time to include the fifth exercise of this lesson. You must carry out this exerciseas the private method to be developed here forms the basis for a lesson that appears later inthe course. Participants with considerable programming experience can tackle the final,optional exercise in the lesson.
Unit 2: Fundamental Object-Oriented Syntax
98 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 111/505
Unit 2Exercise 6
93Create and Use Static Constructors
Business Example
For performance reasons, you do not want to access the database each time an instance iscreated. Therefore, you read all the data just once in the static constructor and store it in astatic attribute
Template:
SAPBC401_BAS_S4
Solution:
SAPBC401_BAS_S5
Task 1
Define an internal table as a private static attribute. Define a static constructor in which you fillthe attribute with the complete content of database table SAPLANE. Use the ABAP Debuggerto call the static constructor.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise.
Define the internal table GT_PLANETYPES as a private class attribute.
To specify the type for the GT_PLANETYPES internal table, define the private tabletypeTY_PLANETYPES in the class definition.
Use the PLANETYPE field as a key for the internal table.
2. Define a static constructor in the LCL_AIRPLANE class.
Implement the constructor in such a way that the GT_PLANETYPES internal table is filledwith all rows from the SAPLANE database table. You can use the ARRAY FETCH techniquefor this purpose.
3. Use the ABAP Debugger to make sure that the static constructor is called correctly andthat the internal table is filled in the main program. Where is the static constructor calledin the main program?
Task 2
Declare and implement a private static method to derive the weight and tank capacity of oneplane type from the GT_PLANETYPES table.
1. Within your LCL_AIRPLANE class, define the private static methodGET_TECHNICAL_ATTRIBUTES.
The signature must consist of the import parameter for the airplane type and the twoexport parameters for weight and tank capacity. Use the transparent table SAPLANE as aguide for specifying the types of these formal parameters.
© Copyright . All rights reserved. 99
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 112/505
The signature should also contain a classical exception that is not class based, which israised if no data is found for the specified airplane type.
2. Implement the method in such a way that the values for the export parameters aredetermined through a single-record access to the internal table GT_PLANETYPES.
If the table does not contain any values for the airplane type, the method should raise an
exception.
Note:Strictly speaking, the correct unit of measure should also be selected andexported. However, due to time constraints you do not need to do it in thisexercise.
Task 3
Replace the database access in the instance constructor by a call of method
GET_TECHNICAL_ATTRIBUTES.
1. Is it possible to call the new method from the main program? Why not?
2. Call the method GET_TECHNICAL_ATTRIBUTES from the constructor to obtain additionaltechnical data. Depending on the outcome, set the corresponding private attributes orraise the exception of the constructor.
3. Observe the execution of the program in the ABAP Debugger .
4. Which alternative solutions could be used to solve the tasks?
SAPBC401_BAS_S5
REPORT sapbc401_bas_s5. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetypeEXCEPTIONS wrong_planetype, display_attributes. CLASS-METHODS:
class_constructor, display_n_o_airplanes, get_n_o_airplanes RETURNINGvalue(rv_count) TYPE i. PRIVATE SECTION.
TYPES: ty_planetypes TYPE STANDARD TABLE OF saplane WITH NON-UNIQUE KEY planetype. CONSTANTS: c_pos_1 TYPE iVALUE 30. DATA: mv_name TYPE string, mv_planetype TYPE saplane-planetype, mv_weight TYPE saplane-weight, mv_tankcap TYPE saplane-tankcap. CLASS-DATA: gv_n_o_airplanes TYPE i,
gt_planetypes TYPE ty_planetypes.
CLASS-METHODS: get_technical_attributes
Unit 2: Fundamental Object-Oriented Syntax
1 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 113/505
IMPORTING iv_type TYPE saplane-planetype EXPORTING ev_weight TYPE saplane-weight ev_tankcap TYPE saplane-tankcap EXCEPTIONS wrong_planetype. ENDCLASS. "lcl_airplane DEFINITION
*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION.
METHOD class_constructor. SELECT * FROM saplane INTO TABLE gt_planetypes. ENDMETHOD. "class_constructor METHOD constructor.
* DATA: ls_planetype TYPE saplane. mv_name = iv_name. mv_planetype =iv_planetype.
* SELECT SINGLE * FROM saplane* INTO ls_planetype* WHERE planetype = iv_planetype.
get_technical_attributes( EXPORTING iv_type = iv_planetype IMPORTING ev_weight = mv_weight ev_tankcap = mv_tankcap EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ELSE.
* mv_weight = ls_planetype-weight.* mv_tankcap = ls_planetype-tankcap. gv_n_o_airplanes = gv_n_o_airplanes+ 1. ENDIF. ENDMETHOD. "constructor METHOD display_attributes.WRITE: / icon_ws_plane AS ICON, / 'Name of Airplane'(001) , AT c_pos_1mv_name, / 'Type of Airplane:'(002), AT c_pos_1 mv_planetype, /'Weight:'(003), AT c_pos_1 mv_weight LEFT-JUSTIFIED, / 'Tankcapacity:'(004), AT c_pos_1 mv_tankcap LEFT-JUSTIFIED. ENDMETHOD."display_attributes METHOD display_n_o_airplanes. SKIP. WRITE: /'Number of airplanes:'(ca1), AT c_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD. "display_n_o_airplanes METHOD get_n_o_airplanes.rv_count = gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes
METHOD get_technical_attributes. DATA: ls_planetype TYPE saplane.
READ TABLE gt_planetypes INTO ls_planetype WITH TABLE KEY planetype = iv_type TRANSPORTING weight tankcap. IF sy-subrc = 0. ev_weight = ls_planetype-weight. ev_tankcap = ls_planetype-tankcap. ELSE. RAISE wrong_planetype.
Lesson: Implementing Class Constructors in Local Classes
© Copyright . All rights reserved. 1 1
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 114/505
ENDIF. ENDMETHOD. "get_technical_attributes ENDCLASS. "lcl_airplane IMPLEMENTATION DATA: go_airplane TYPE REF TOlcl_airplane, gt_airplanes TYPE TABLE OF REF TO lcl_airplane, gv_countTYPE i. START-OF-SELECTION. *******************lcl_airplane=>display_n_o_airplanes( ). CREATE OBJECT go_airplaneEXPORTING iv_name = 'LH Berlin' iv_planetype = 'A321' EXCEPTIONS
wrong_planetype = 1. IF sy-subrc = 0. APPEND go_airplane TOgt_airplanes. ENDIF. CREATE OBJECT go_airplane EXPORTING iv_name = 'AANew York' iv_planetype = '747-400' EXCEPTIONS wrong_planetype = 1. IFsy-subrc = 0. APPEND go_airplane TO gt_airplanes. ENDIF. CREATE OBJECTgo_airplane EXPORTING iv_name = 'US Hercules' iv_planetype ='747-200F' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0. APPENDgo_airplane TO gt_airplanes. ENDIF. LOOP AT gt_airplanes INTOgo_airplane. go_airplane->display_attributes( ). ENDLOOP. gv_count =lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: / 'Number ofairplanes'(ca1), gv_count.
Unit 2: Fundamental Object-Oriented Syntax
1 2 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 115/505
Unit 2Solution 6
97Create and Use Static Constructors
Business Example
For performance reasons, you do not want to access the database each time an instance iscreated. Therefore, you read all the data just once in the static constructor and store it in astatic attribute
Template:
SAPBC401_BAS_S4
Solution:
SAPBC401_BAS_S5
Task 1
Define an internal table as a private static attribute. Define a static constructor in which you fillthe attribute with the complete content of database table SAPLANE. Use the ABAP Debuggerto call the static constructor.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise.
Define the internal table GT_PLANETYPES as a private class attribute.
To specify the type for the GT_PLANETYPES internal table, define the private tabletypeTY_PLANETYPES in the class definition.
Use the PLANETYPE field as a key for the internal table.
a) See the source code extract from the model solution.
2. Define a static constructor in the LCL_AIRPLANE class.
Implement the constructor in such a way that the GT_PLANETYPES internal table is filledwith all rows from the SAPLANE database table. You can use the ARRAY FETCH techniquefor this purpose.
a) See the source code extract from the model solution.
3. Use the ABAP Debugger to make sure that the static constructor is called correctly andthat the internal table is filled in the main program. Where is the static constructor calledin the main program?
a) Before the class is accessed for the first time (before DISPLAY_N_O_AIRPLANES inthis case).
Task 2
Declare and implement a private static method to derive the weight and tank capacity of oneplane type from the GT_PLANETYPES table.
1. Within your LCL_AIRPLANE class, define the private static methodGET_TECHNICAL_ATTRIBUTES.
© Copyright . All rights reserved. 1 3
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 116/505
The signature must consist of the import parameter for the airplane type and the twoexport parameters for weight and tank capacity. Use the transparent table SAPLANE as aguide for specifying the types of these formal parameters.
The signature should also contain a classical exception that is not class based, which israised if no data is found for the specified airplane type.
a) See the source code extract from the model solution.2. Implement the method in such a way that the values for the export parameters are
determined through a single-record access to the internal table GT_PLANETYPES.
If the table does not contain any values for the airplane type, the method should raise anexception.
a) See the source code extract from the model solution.
Note:Strictly speaking, the correct unit of measure should also be selected andexported. However, due to time constraints you do not need to do it in thisexercise.
Task 3
Replace the database access in the instance constructor by a call of methodGET_TECHNICAL_ATTRIBUTES.
1. Is it possible to call the new method from the main program? Why not?
a) This would only be possible if the method was public. Because it is a private method, itcan only be called from within the LCL_AIRPLANE class.
2. Call the method GET_TECHNICAL_ATTRIBUTES from the constructor to obtain additionaltechnical data. Depending on the outcome, set the corresponding private attributes orraise the exception of the constructor.
a) See the source code extract from the model solution.
3. Observe the execution of the program in the ABAP Debugger .
a) Carry out this step in the usual manner. Additional information on the ABAP Debuggeris available in the SAP Library.
4. Which alternative solutions could be used to solve the tasks?
a) Define GET_TECHNCAL_ATTRIBUTES as instance method without the PLANETYPE
import parameter.If the method was defined as an instance method, it could access the MV_PLANETYPEattribute directly (as ME->MV_PLANETYPE). In that case, the import parameter wouldnot be needed.
b) Do not use a method to read GT_PLANETYPES.
In the instance constructor, you could access the class attribute GT_PLANETYPESdirectly (as ME->GT_PLANETYPES).
SAPBC401_BAS_S5
REPORT sapbc401_bas_s5. TYPE-POOLS icon.*------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*
Unit 2: Fundamental Object-Oriented Syntax
1 4 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 117/505
CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetypeEXCEPTIONS wrong_planetype, display_attributes. CLASS-METHODS:
class_constructor, display_n_o_airplanes, get_n_o_airplanes RETURNINGvalue(rv_count) TYPE i. PRIVATE SECTION.
TYPES: ty_planetypes TYPE STANDARD TABLE OF saplane WITH NON-UNIQUE KEY planetype. CONSTANTS: c_pos_1 TYPE iVALUE 30. DATA: mv_name TYPE string, mv_planetype TYPE saplane-planetype, mv_weight TYPE saplane-weight, mv_tankcap TYPE saplane-tankcap. CLASS-DATA: gv_n_o_airplanes TYPE i,
gt_planetypes TYPE ty_planetypes.
CLASS-METHODS: get_technical_attributes IMPORTING iv_type TYPE saplane-planetype EXPORTING ev_weight TYPE saplane-weight ev_tankcap TYPE saplane-tankcap EXCEPTIONS wrong_planetype. ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION.
METHOD class_constructor. SELECT * FROM saplane INTO TABLE gt_planetypes. ENDMETHOD. "class_constructor METHOD constructor.
* DATA: ls_planetype TYPE saplane. mv_name = iv_name. mv_planetype =iv_planetype.
* SELECT SINGLE * FROM saplane* INTO ls_planetype* WHERE planetype = iv_planetype.
get_technical_attributes( EXPORTING iv_type = iv_planetype IMPORTING ev_weight = mv_weight ev_tankcap = mv_tankcap EXCEPTIONS wrong_planetype = 1 ).
IF sy-subrc <> 0. RAISE wrong_planetype. ELSE.
Lesson: Implementing Class Constructors in Local Classes
© Copyright . All rights reserved. 1 5
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 118/505
* mv_weight = ls_planetype-weight.* mv_tankcap = ls_planetype-tankcap. gv_n_o_airplanes = gv_n_o_airplanes+ 1. ENDIF. ENDMETHOD. "constructor METHOD display_attributes.WRITE: / icon_ws_plane AS ICON, / 'Name of Airplane'(001) , AT c_pos_1mv_name, / 'Type of Airplane:'(002), AT c_pos_1 mv_planetype, /'Weight:'(003), AT c_pos_1 mv_weight LEFT-JUSTIFIED, / 'Tankcapacity:'(004), AT c_pos_1 mv_tankcap LEFT-JUSTIFIED. ENDMETHOD."display_attributes METHOD display_n_o_airplanes. SKIP. WRITE: /'Number of airplanes:'(ca1), AT c_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD. "display_n_o_airplanes METHOD get_n_o_airplanes.rv_count = gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes
METHOD get_technical_attributes. DATA: ls_planetype TYPE saplane.
READ TABLE gt_planetypes INTO ls_planetype WITH TABLE KEY planetype = iv_type TRANSPORTING weight tankcap. IF sy-subrc = 0. ev_weight = ls_planetype-weight. ev_tankcap = ls_planetype-tankcap. ELSE. RAISE wrong_planetype. ENDIF. ENDMETHOD. "get_technical_attributes ENDCLASS. "lcl_airplane IMPLEMENTATION DATA: go_airplane TYPE REF TOlcl_airplane, gt_airplanes TYPE TABLE OF REF TO lcl_airplane, gv_countTYPE i. START-OF-SELECTION. *******************lcl_airplane=>display_n_o_airplanes( ). CREATE OBJECT go_airplaneEXPORTING iv_name = 'LH Berlin' iv_planetype = 'A321' EXCEPTIONSwrong_planetype = 1. IF sy-subrc = 0. APPEND go_airplane TOgt_airplanes. ENDIF. CREATE OBJECT go_airplane EXPORTING iv_name = 'AANew York' iv_planetype = '747-400' EXCEPTIONS wrong_planetype = 1. IFsy-subrc = 0. APPEND go_airplane TO gt_airplanes. ENDIF. CREATE OBJECTgo_airplane EXPORTING iv_name = 'US Hercules' iv_planetype ='747-200F' EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0. APPENDgo_airplane TO gt_airplanes. ENDIF. LOOP AT gt_airplanes INTOgo_airplane. go_airplane->display_attributes( ). ENDLOOP. gv_count =lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: / 'Number ofairplanes'(ca1), gv_count.
Unit 2: Fundamental Object-Oriented Syntax
1 6 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 119/505
LESSON SUMMARYYou should now be able to:
● Create and use static constructors
Lesson: Implementing Class Constructors in Local Classes
© Copyright . All rights reserved. 1 7
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 120/505
Unit 2: Fundamental Object-Oriented Syntax
1 8 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 121/505
Unit 2
103Learning Assessment
1. The CLASS statement can be nested, that is, you cannot define a class within a class.
Determine whether this statement is true or false.
X True
X False
2. Which one of the following syntax elements define the static attributes?Choose the correct answer.
X A CLASS-DATA
X B DATA
X C LIKE
3. Which of the following options is used to create an object?
Choose the correct answer.
X A CREATE OBJECT ref_name
X B APPEND ref_name
X C CLASS ref_name
4. The Garbage Collector is a system routine that starts automatically if the runtime systemdoes not have important tasks to carry out.
Determine whether this statement is true or false.
X True
X False
5. Independent references are references that have been defined within a class.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 1 9
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 122/505
6. Which of the following options is used to administer objects in the internal table?
Choose the correct answers.
X A LOOP
X B APPEND
X C CLASS
X D READ
7. You cannot create and address the objects using reference variables.
Determine whether this statement is true or false.
X True
X False
8. During program runtime, you use the class to create discrete objects (instances) in thememory. This process is called instantiation.
Determine whether this statement is true or false.
X True
X False
9. Which of the following parameters are mutually exclusive?
Choose the correct answers.
X A RECEIVING
X B IMPORTING
X C EXCEPTIONS
X D CHANGING
10. When calling a static method from within the class, you can omit the class name.
Determine whether this statement is true or false.
X True
X False
Unit 2: Learning Assessment
11 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 123/505
11. Which of the following expression(s) is used to call functional methods directly?
Choose the correct answers.
X A ELSEIF
X B COMPUTE
X C MOVE
X D WHILE
12. You can describe methods that have a _________ parameter as functional methods.
Choose the correct answer.
X A EXPORTING
X B CHANGING
X C RETURNING
13. You have to pass the RETURNING parameter using the VALUE addition, that is, pass byvalue.
Determine whether this statement is true or false.
X True
X False
14. You can access static attributes using ____________.
Choose the correct answer.
X A classname=>method_name
X B classname=>static_attribute
X C ref->instance_attribute
15. The _____________ is a special instance method in a class.
Choose the correct answer.
X A constructor
X B function
X C attributes
Unit 2: Learning Assessment
© Copyright . All rights reserved. 111
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 124/505
16. The constructor is automatically called at runtime with the CREATE OBJECT statement.
Determine whether this statement is true or false.
X True
X False
17. Which of the following points do you consider when defining static constructors?
Choose the correct answer.
X A Each class has not more than one static constructor.
X B The static constructor must be defined in the private area.
X C The constructor’s signature can have importing parameters or exceptions.
X D The static constructor can be called explicitly.
18. The constructor’s signature can have importing parameters or exceptions.
Determine whether this statement is true or false.
X True
X False
Unit 2: Learning Assessment
112 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 125/505
Unit 2
107Learning Assessment- Answers
1. The CLASS statement can be nested, that is, you cannot define a class within a class.
Determine whether this statement is true or false.
X True
X False
2. Which one of the following syntax elements define the static attributes?
Choose the correct answer.
X A CLASS-DATA
X B DATA
X C LIKE
3. Which of the following options is used to create an object?
Choose the correct answer.
X A CREATE OBJECT ref_name
X B APPEND ref_name
X C CLASS ref_name
4. The Garbage Collector is a system routine that starts automatically if the runtime systemdoes not have important tasks to carry out.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 113
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 126/505
5. Independent references are references that have been defined within a class.
Determine whether this statement is true or false.
X True
X False
6. Which of the following options is used to administer objects in the internal table?
Choose the correct answers.
X A LOOP
X B APPEND
X C CLASS
X D READ
7. You cannot create and address the objects using reference variables.
Determine whether this statement is true or false.
X True
X False
8. During program runtime, you use the class to create discrete objects (instances) in thememory. This process is called instantiation.
Determine whether this statement is true or false.
X True
X False
9. Which of the following parameters are mutually exclusive?
Choose the correct answers.
X A RECEIVING
X B IMPORTING
X C EXCEPTIONS
X D CHANGING
Unit 2: Learning Assessment- Answers
114 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 127/505
10. When calling a static method from within the class, you can omit the class name.
Determine whether this statement is true or false.
X True
X False
11. Which of the following expression(s) is used to call functional methods directly?
Choose the correct answers.
X A ELSEIF
X B COMPUTE
X C MOVE
X D WHILE
12. You can describe methods that have a _________ parameter as functional methods.
Choose the correct answer.
X A EXPORTING
X B CHANGING
X C RETURNING
13. You have to pass the RETURNING parameter using the VALUE addition, that is, pass byvalue.
Determine whether this statement is true or false.
X True
X False
14. You can access static attributes using ____________.
Choose the correct answer.
X A classname=>method_name
X B classname=>static_attribute
X C ref->instance_attribute
Unit 2: Learning Assessment- Answers
© Copyright . All rights reserved. 115
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 128/505
15. The _____________ is a special instance method in a class.
Choose the correct answer.
X A constructor
X B function
X C attributes
16. The constructor is automatically called at runtime with the CREATE OBJECT statement.
Determine whether this statement is true or false.
X True
X False
17. Which of the following points do you consider when defining static constructors?
Choose the correct answer.
X A Each class has not more than one static constructor.
X B The static constructor must be defined in the private area.
X C The constructor’s signature can have importing parameters or exceptions.
X D The static constructor can be called explicitly.
18. The constructor’s signature can have importing parameters or exceptions.
Determine whether this statement is true or false.
X True
X False
Unit 2: Learning Assessment- Answers
116 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 129/505
UNIT 3 Inheritance and Casting
Lesson 1
Implementing Inheritance 118Exercise 7: Implement Inheritance 127
Lesson 2
Implementing Up-Casts Using Inheritance 140
Exercise 8: Implement Up-Casts 145
Lesson 3
Implementing Polymorphism Using Inheritance 151Exercise 9: Implement Polymorphism Using Inheritance 155
Lesson 4
Implementing Down-Casts Using Inheritance 162Exercise 10: Implement Down-Casts 167
UNIT OBJECTIVES
● Explain generalization and specialization
● Implement inheritance
● Access elements of classes in inheritance
●
Implement up-casts using inheritance● Explain polymorphism
● Implement polymorphism using inheritance
● Implement down-casts using inheritance
● Model class hi erarchies
© Copyright . All rights reserved. 117
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 130/505
Unit 3Lesson 1
112Implementing Inheritance
LESSON OVERVIEWThis lesson explains the concept of inheritance and casting. This lesson also explains howinheritance is implemented.
The idea behind compass courses is that the individual lessons are not restricted to a certaincontext. In this case, that the participants could theoretically understand the lesson aboutinterfaces without having covered the lesson on inheritance. To facilitate this, someinformation is repeated throughout the units, which means that the second lesson can oftenbe compressed into a few sentences.
Explain the users that except for the different syntax, interfaces are identical to abstractsuper classes that have exclusively public abstract methods.
Since the lessons are not dependent on a certain context, repeat the essential content anddemonstrations. However, throughout the whole course, refer to regular inheritance inrelation to interfaces as often as possible.
This serves to clarify the connection rather than to save time. This should make it easier forparticipants to understand.
This lesson contains a lot of new material for the participants, so you may see the first signs
of irritation or waning interest. In such cases, point out that this unit deals with generalconcepts of object-orientation. The knowledge gained can be very useful in other object-oriented languages as well.
Work with participants to deduce the purpose of every single concept and determine wherethey would use them. Occasionally, comparisons with the procedural programming modelcan also help to create a clearer understanding.
The exercises are there to show that the material really is fairly simple. Once participantsrealize that they do understand the course content, you might observe increases inmotivation levels especially from those participants who were anxious about the course.
Business Example
As a developer, implement inheritance for airplane class. For this reason, you require thefollowing knowledge:
● An understanding of inheritance
● An understanding of casting
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain generalization and specialization
118 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 131/505
● Implement inheritance
● Access elements of classes in inheritance
Generalization and Specialization
Figure 61: Example of Generalization/Specialization
The question of multiple inheritance might arise here. Multiple inheritance is neithersupported in Java nor in ABAP Objects. However, it is supported in C++. With this, a class can
inherit from several superclasses.
Specialization (UML) is a relationship in which one class (subclass) inherits all the maincharacteristics of another class (superclass). The subclass can also add new components(attributes, methods, and so on) and replace the implementations with inherited methods. Inthe latter case, rename the method name in the UML diagram within the subclass.
Specialization is an implementation relationship that emphasizes similarities of the classes. Inthe example above, the similarities of classes LCL_CAR, LCL_TRUCK, and LCL_BUS areextracted to a superclass, LCL_VEHICLE. Therefore, the components they have in commonare only defined and implemented in the superclass. They also exist in all subclasses.
Specialization is described as an "is a" relationship. For example, a truck is a specific vehicle.Reversing the point of view is referred to as generalization.
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 119
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 132/505
Characteristics of Generalization/Specialization
Figure 62: Characteristics of Generalization/Specialization
Generalization/specialization, if used properly, provides a significantly better structure foryour software. This use is done because you must store commonly used elements only oncein a central location in the superclass and are then automatically available to all subclasses.Changes made at a later stage have an immediate effect on the subclasses. Therefore, do notalter the semantics when you change a superclass.
You need exact knowledge of the implementation of the superclass to decide whether theinherited components from the superclass are sufficient for the subclass or if they must beextended. Generalization/specialization, therefore provides strong links between thesuperclass and the subclass.
When you develop additional subclasses, adapt the superclasses, too. Therefore, the creationof a subclass sometimes leads to additional requirements for the superclass. For example,when a subclass requires certain protected components or when the details ofimplementation of superclass are required to change the method implementations insubclasses. The developer of superclass cannot predict everything that the subclasses laterrequires from the superclass.
The characteristics of generalization/specialization are as follows:● Common components only exist once in the superclass, so they can be maintained
centrally.
●
Components in the superclasses are available in all subclasses. This approach avoidsredundant implementations.
● Subclasses contain extensions or changes (programming by difference).
● Subclasses are dependent on superclasses (white box reuse).
Unit 3: Inheritance and Casting
12 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 133/505
Implementation of Inheritance
Figure 63: Inheritance – Syntax
In ABAP Objects, an inheritance relationship is defined for a subclass using the INHERITINGFROM addition, followed by the superclass that is directly above the subclass. Inheritancehierarchies of varying complexity arise when this superclass inherits from another superclassabove it. In contrast, there is no multiple inheritance in ABAP Objects. That is, only onesuperclass can be specified directly above a class. However, you can use interfaces in ABAPObjects to simulate multiple inheritance.
You should use inheritance to implement generalization and specialization relationships. Asuperclass is a generalization of its subclasses. The subclasses are in turn differentspecializations of their superclasses. Thus, only additions or changes are permitted in ABAPObjects, which means that you can never remove anything from a superclass in a subclass.
Inheritance is a one-sided relationship. In other words, subclasses recognize their directsuperclasses but superclasses do not recognize their subclasses. In this example, thesubclass also contains the SET_TYPE method. The subclass also defines the GET_CARGOmethod.
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 121
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 134/505
Redefinition of Methods
Figure 64: Redefining Methods
Redefinition is when the implementation of an inherited instance method is changed for thesubclass, without changing the signature. At the same time, the visibility section for thesuperclass must remain the same. Therefore, redefinition is not possible within the PRIVATESECTION.
When you use the REDEFINITION addition, specify a new implementation part for theinherited method. Since the signature may be changed, you do not need to define the methodparameters and exceptions again. Within the redefined implementation part of the method,you can use the predefined prefix super->... to access components in the superclass directlyabove where you are working. You must often do this while redefining a method to call theoriginal method of the superclass.
Preserving Semantics During Redefinition
Figure 65: Preserving Semantics During Redefinition
Unit 3: Inheritance and Casting
122 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 135/505
In this example, both redefined methods output provide completely different information. Theimportant point is that the semantics of the method stay the same.
Definition of Subclass Constructors
Figure 66: Definition of the Constructor in Subclasses
In most cases, a redefinition, as described for the methods would not be useful in the case ofthe constructor. Either you can use the constructor of superclass without any changes, or youcan expand the subclass and other parameters that are now required in the signature of
superclass.In ABAP Objects, the constructor is not inherited like normal methods. Any class can defineits own constructor that is fully independent from the definition of the constructor in itssuperclass. A subclass can even define a constructor if there is no constructor in thesuperclass.
However, when implementing the subclass constructor, it is mandatory to call the constructorof the immediate superclass. By doing so, it is ensured that the constructor of class is alwaysexecuted, whether the created object is an instance of the class itself, or an instance of one ofits subclasses.
Because of this enforced call of the superclass constructor, the subclass constructor
normally just add parameters to the signature of the superclass constructor rather than becompletely different.
Hint:In this context, the concept of overloading is of relevance. With overloading, amethod can have several definitions with different signatures and thus alsodifferent implementations. The concept of overloading is not supported in ABAPObjects. The usual work-around is one signature with different sets of optionalparameters.
In contrast to instance constructors, the static constructor in the superclass is calledautomatically. This means that the runtime system automatically ensures that the static
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 123
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 136/505
constructors of all its superclasses have already been executed before the static constructorin a particular class is executed.
Rules for Calling the Constructor
Figure 67: Rules for Calling the Constructor
If a subclass has not changed its instance constructor, you leave the constructor unchangedand adopt it from the superclass. Therefore, the implementation is executed from thesuperclass.
Demonstration: How to Implement Inheritance
To demonstrate how to implement inheritance, implement suitable parts of programSAPBC401_INH_D1.
Unit 3: Inheritance and Casting
124 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 137/505
Inheritance and Visibility
Figure 68: Inheritance and Visibility
Inheritance provides an extension of the visibility concept. There are protected components(PROTECTED SECTION). The visibility of protected components lies between public andprivate components. Protected components are visible to all subclasses and the class itself.
When defining local classes in ABAP Objects, follow the syntactical sequence of PUBLICSECTION, PROTECTED SECTION, and PRIVATE SECTION.
Protected Versus Private Section
Figure 69: Protected Versus Private Section
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 125
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 138/505
All components of superclass are available to the subclass is not related to the visibility of thecomponent. A subclass also receives the private components of its superclass. However, youcannot address these private components in the syntax of the subclass. You can only addressthe private components of superclasses indirectly using public or protected methods fromthe superclass, which in turn, can access the private attributes. These restrictions arenecessary to ensure that centralized maintenance is possible.
In this example, it is possible to access the protected constant C_POS_1 in superclassLCL_VEHICLE directly from its subclass LCL_BUS. On the other hand, the only way to accessthe private MV_MAKE and MV_MODEL attributes from the subclasses of LCL_VEHICLE are tocall methods of LCL_VEHICLE. These methods have to be public or protected.
Using the private visibility section, you can change superclasses without the need to know thesubclasses. As long as the changes you make do not affect the semantics, you do not need toadapt the subclasses. This is because they only indirectly access the private componentsfrom the superclass.
Inheritance and Static Components
Your demonstration program should now resemble the executable programSAPBC401_INH_D1.
Once again, remind participants of the benefit of below mentioned points. For example,centralized maintenance of the general components of all vehicles.
At this point, we recommend having the participants do the first exercise of this lesson.
There is only one static component per program context.
Summary of static components and inheritance are as follows:● A class that defines a public or protected static attribute shares this attribute with all its
subclasses.
● You cannot define static methods.
● The static constructor of a superclass is executed when the superclass or one of itssubclasses is accessed for the first time.
● A subclass can always have a static constructor whether the superclass has a staticconstructor or not.
● If a subclass and its superclass have a static constructor they are both executed when the
first access to the subclass is also the first access to the superclass.
Demonstration: How to Debug Inheritance
To demonstrate how to debug inheritance, use suitable parts of programSAPBC401_INH_D1.
Unit 3: Inheritance and Casting
126 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 139/505
Unit 3Exercise 7
119Implement Inheritance
Business Example
You must refine your airplane management program. Put classes for specific airplanes inrelation to a general airplane class.
Template
SAPBC401_BAS_S5
Solution
SAPBC401_INH_S1
Task 1
Define the local class LCL_PASSENGER_PLANE for passenger planes. Define the class as asubclass of LCL_AIRPLANE. Add specific attributes and methods and redefine theDISPLAY_ATTRIBUTES method.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the template program.
Define a new local class LCL_PASSENGER_PLANE and make it a subclass of the alreadyexisting LCL_AIRPLANE.
2. Is there a specific sequence in which you have to define the classes in the source code?
3. The class must have a private instance attribute, MV_SEATS, with the same type as thetable field SFLIGHT-SEATSMAX.
4. Define and implement an instance constructor that assigns values to all instanceattributes in the class.
5. Redefine method DISPLAY_ATTRIBUTES so that all instance attributes are displayedusing the WRITE statement.
Make sure the output of specific attributes are aligned with the output from thesuperclass. Therefore, change the visibility of the C_POS_1 constant so that you can use itin your subclass.
Task 2
In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE for cargo planes.
1. The class must have a private instance attribute, MV_CARGO, with the same type as thetable field SCPLANE-CARGOMAX.
© Copyright . All rights reserved. 127
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 140/505
2. Define and implement an instance constructor that assigns values to all instanceattributes in the class.
3. Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed using theWRITE statement.
Task 3
Create instances of your new classes and display their attributes.
1. In the main program, define a suitably typed reference variable for each of your newclasses.
2. Before instantiating any objects, call the static method DISPLAY_N_O_AIRPLANES.
3. Use the two references to create an instance of each of the subclassesLCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourself how to fill theattributes.
4. Call the DISPLAY_ATTRIBUTES method for both instances.
5. Call the static method DISPLAY_ATTRIBUTES second time.
Task 4
Debug your program.
1. Observe the program flow in the ABAP Debugger , paying special attention to the call of theDISPLAY_ATTRIBUTES method.
2. Could the method GET_TECHNICAL_ATTRIBUTES be called directly from the redefinedmethod DISPLAY_ATTRIBUTES of the subclasses?
SAPBC401_INH_S1
REPORT sapbc401_inh_s1. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetypeEXCEPTIONS wrong_planetype, display_attributes. CLASS-METHODS:class_constructor, display_n_o_airplanes, get_n_o_airplanes RETURNINGvalue(rv_count) TYPE i.
PROTECTED SECTION.
CONSTANTS: c_pos_1 TYPE i VALUE 30. PRIVATE SECTION. TYPES: ty_planetypes TYPESTANDARD TABLE OF saplane WITH NON-UNIQUE KEY planetype. DATA: mv_nameTYPE string, mv_planetype TYPE saplane-planetype, mv_weight TYPEsaplane-weight, mv_tankcap TYPE saplane-tankcap. CLASS-DATA:
Unit 3: Inheritance and Casting
128 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 141/505
gv_n_o_airplanes TYPE i, gt_planetypes TYPE ty_planetypes. CLASS-METHODS: get_technical_attributes IMPORTING iv_type TYPE saplane-planetype EXPORTING ev_weight TYPE saplane-weight ev_tankcap TYPEsaplane-tankcap EXCEPTIONS wrong_planetype. ENDCLASS. "lcl_airplaneDEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION *
*------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. METHOD class_constructor. SELECT *FROM saplane INTO TABLE gt_planetypes. ENDMETHOD. "class_constructorMETHOD constructor. mv_name = iv_name. mv_planetype = iv_planetype.get_technical_attributes( EXPORTING iv_type = iv_planetype IMPORTINGev_weight = mv_weight ev_tankcap = mv_tankcap EXCEPTIONSwrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ELSE.gv_n_o_airplanes = gv_n_o_airplanes + 1. ENDIF. ENDMETHOD."constructor METHOD display_attributes. WRITE: / icon_ws_plane ASICON, / 'Name of Airplane'(001) , AT c_pos_1 mv_name, / 'Type ofAirplane:'(002), AT c_pos_1 mv_planetype, / 'Weight:'(003), AT c_pos_1mv_weight LEFT-JUSTIFIED, / 'Tank capacity:'(004), AT c_pos_1mv_tankcap LEFT-JUSTIFIED. ENDMETHOD. "display_attributes METHODdisplay_n_o_airplanes. SKIP. WRITE: / 'Number of airplanes:'(ca1), AT
c_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD."display_n_o_airplanes METHOD get_n_o_airplanes. rv_count =gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes METHODget_technical_attributes. DATA: ls_planetype TYPE saplane. READ TABLEgt_planetypes INTO ls_planetype WITH TABLE KEY planetype = iv_typeTRANSPORTING weight tankcap. IF sy-subrc = 0. ev_weight = ls_planetype-weight. ev_tankcap = ls_planetype-tankcap. ELSE. RAISEwrong_planetype. ENDIF. ENDMETHOD. "get_technical_attributes ENDCLASS."lcl_airplane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -***- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
METHODS:
constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_cargo TYPE s_plan_car EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: mv_cargo TYPE s_plan_car.
ENDCLASS. "lcl_cargo_plane DEFINITION
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 129
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 142/505
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor. super->constructor( EXPORTING iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF. mv_cargo = iv_cargo. ENDMETHOD. "constructor
METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Cargo:'(005), AT c_pos_1 mv_cargo LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributes
ENDCLASS. "lcl_cargo_plane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_passenger_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -*CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
METHODS: constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_seats TYPE s_seatsmax EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION. PRIVATE SECTION.
DATA: mv_seats TYPE s_seatsmax.ENDCLASS. "lcl_passenger_plane DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_passenger_plane IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor.
Unit 3: Inheritance and Casting
13 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 143/505
super->constructor( EXPORTING iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0.
RAISE wrong_planetype. ENDIF. mv_seats = iv_seats. ENDMETHOD. "constructor
METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Seats:'(006), AT c_pos_1 mv_seats LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributesENDCLASS. "lcl_passenger_plane IMPLEMENTATION DATA: go_airplane TYPE REF TO lcl_airplane,
go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPE REF TO lcl_passenger_plane, gt_airplanes TYPE TABLE OFREF TO lcl_airplane, gv_count TYPE i. START-OF-SELECTION.******************* lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype = 1.
IF sy-subrc = 0.* do nothing just now ENDIF.
CREATE OBJECT go_cargo EXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo = 533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.* do nothing just now ENDIF.
go_passenger->display_attributes( ). go_cargo->display_attributes( ). gv_count = lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: /'Number of airplanes'(ca1), gv_count.
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 131
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 144/505
Unit 3: Inheritance and Casting
132 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 145/505
Unit 3Solution 7
125Implement Inheritance
Business Example
You must refine your airplane management program. Put classes for specific airplanes inrelation to a general airplane class.
Template
SAPBC401_BAS_S5
Solution
SAPBC401_INH_S1
Task 1
Define the local class LCL_PASSENGER_PLANE for passenger planes. Define the class as asubclass of LCL_AIRPLANE. Add specific attributes and methods and redefine theDISPLAY_ATTRIBUTES method.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the template program.
Define a new local class LCL_PASSENGER_PLANE and make it a subclass of the alreadyexisting LCL_AIRPLANE.
a) See the source code extract from the model solution.
2. Is there a specific sequence in which you have to define the classes in the source code?
You first define the superclass. Otherwise, the syntax check will not know it when you referto superclass in the INHERITING FROM part of the subclass definition.
3. The class must have a private instance attribute, MV_SEATS, with the same type as thetable field SFLIGHT-SEATSMAX.
a) See the source code extract from the model solution.
4. Define and implement an instance constructor that assigns values to all instanceattributes in the class.
a) See the source code extract from the model solution.
5. Redefine method DISPLAY_ATTRIBUTES so that all instance attributes are displayedusing the WRITE statement.
Make sure the output of specific attributes are aligned with the output from thesuperclass. Therefore, change the visibility of the C_POS_1 constant so that you can use itin your subclass.
a) See the source code extract from the model solution.
© Copyright . All rights reserved. 133
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 146/505
Task 2
In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE for cargo planes.
1. The class must have a private instance attribute, MV_CARGO, with the same type as the
table field SCPLANE-CARGOMAX.a) See the source code extract from the model solution.
2. Define and implement an instance constructor that assigns values to all instanceattributes in the class.
a) See the source code extract from the model solution.
3. Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed using theWRITE statement.
a) See the source code extract from the model solution.
Task 3
Create instances of your new classes and display their attributes.
1. In the main program, define a suitably typed reference variable for each of your newclasses.
a) See the source code extract from the model solution.
2. Before instantiating any objects, call the static method DISPLAY_N_O_AIRPLANES.
a) See the source code extract from the model solution.
3. Use the two references to create an instance of each of the subclasses
LCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourself how to fill theattributes.
a) See the source code extract from the model solution.
4. Call the DISPLAY_ATTRIBUTES method for both instances.
a) See the source code extract from the model solution.
5. Call the static method DISPLAY_ATTRIBUTES second time.
a) See the source code extract from the model solution.
Task 4Debug your program.
1. Observe the program flow in the ABAP Debugger , paying special attention to the call of theDISPLAY_ATTRIBUTES method.
a) Carry out this step in the usual manner.
2. Could the method GET_TECHNICAL_ATTRIBUTES be called directly from the redefinedmethod DISPLAY_ATTRIBUTES of the subclasses?
No, because the method is private in the superclass.
Unit 3: Inheritance and Casting
134 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 147/505
SAPBC401_INH_S1
REPORT sapbc401_inh_s1. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetypeEXCEPTIONS wrong_planetype, display_attributes. CLASS-METHODS:class_constructor, display_n_o_airplanes, get_n_o_airplanes RETURNINGvalue(rv_count) TYPE i.
PROTECTED SECTION.
CONSTANTS: c_pos_1 TYPE i VALUE 30. PRIVATE SECTION. TYPES: ty_planetypes TYPESTANDARD TABLE OF saplane WITH NON-UNIQUE KEY planetype. DATA: mv_name
TYPE string, mv_planetype TYPE saplane-planetype, mv_weight TYPEsaplane-weight, mv_tankcap TYPE saplane-tankcap. CLASS-DATA:gv_n_o_airplanes TYPE i, gt_planetypes TYPE ty_planetypes. CLASS-METHODS: get_technical_attributes IMPORTING iv_type TYPE saplane-planetype EXPORTING ev_weight TYPE saplane-weight ev_tankcap TYPEsaplane-tankcap EXCEPTIONS wrong_planetype. ENDCLASS. "lcl_airplaneDEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. METHOD class_constructor. SELECT *FROM saplane INTO TABLE gt_planetypes. ENDMETHOD. "class_constructorMETHOD constructor. mv_name = iv_name. mv_planetype = iv_planetype.get_technical_attributes( EXPORTING iv_type = iv_planetype IMPORTING
ev_weight = mv_weight ev_tankcap = mv_tankcap EXCEPTIONSwrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ELSE.gv_n_o_airplanes = gv_n_o_airplanes + 1. ENDIF. ENDMETHOD."constructor METHOD display_attributes. WRITE: / icon_ws_plane ASICON, / 'Name of Airplane'(001) , AT c_pos_1 mv_name, / 'Type ofAirplane:'(002), AT c_pos_1 mv_planetype, / 'Weight:'(003), AT c_pos_1mv_weight LEFT-JUSTIFIED, / 'Tank capacity:'(004), AT c_pos_1mv_tankcap LEFT-JUSTIFIED. ENDMETHOD. "display_attributes METHODdisplay_n_o_airplanes. SKIP. WRITE: / 'Number of airplanes:'(ca1), ATc_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD."display_n_o_airplanes METHOD get_n_o_airplanes. rv_count =gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes METHODget_technical_attributes. DATA: ls_planetype TYPE saplane. READ TABLEgt_planetypes INTO ls_planetype WITH TABLE KEY planetype = iv_type
TRANSPORTING weight tankcap. IF sy-subrc = 0. ev_weight = ls_planetype-weight. ev_tankcap = ls_planetype-tankcap. ELSE. RAISEwrong_planetype. ENDIF. ENDMETHOD. "get_technical_attributes ENDCLASS."lcl_airplane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -**
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 135
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 148/505
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
METHODS:
constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_cargo TYPE s_plan_car EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: mv_cargo TYPE s_plan_car.
ENDCLASS. "lcl_cargo_plane DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor. super->constructor( EXPORTING iv_name = iv_name
iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF. mv_cargo = iv_cargo. ENDMETHOD. "constructor
METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Cargo:'(005), AT c_pos_1 mv_cargo LEFT-JUSTIFIED.
ULINE. ENDMETHOD. "display_attributes
ENDCLASS. "lcl_cargo_plane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_passenger_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
METHODS: constructor
Unit 3: Inheritance and Casting
136 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 149/505
IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_seats TYPE s_seatsmax EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION. PRIVATE SECTION.
DATA: mv_seats TYPE s_seatsmax.ENDCLASS. "lcl_passenger_plane DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_passenger_plane IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor. super->constructor( EXPORTING iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF. mv_seats = iv_seats. ENDMETHOD. "constructor
METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Seats:'(006), AT c_pos_1 mv_seats LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributesENDCLASS. "lcl_passenger_plane IMPLEMENTATION DATA: go_airplane TYPE REF TO lcl_airplane,
go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPE REF TO lcl_passenger_plane, gt_airplanes TYPE TABLE OFREF TO lcl_airplane, gv_count TYPE i. START-OF-SELECTION.******************* lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype = 1.
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 137
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 150/505
IF sy-subrc = 0.* do nothing just now ENDIF.
CREATE OBJECT go_cargo EXPORTING
iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo = 533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.* do nothing just now ENDIF.
go_passenger->display_attributes( ). go_cargo->display_attributes( ). gv_count = lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: /'Number of airplanes'(ca1), gv_count.
Unit 3: Inheritance and Casting
138 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 151/505
LESSON SUMMARYYou should now be able to:
● Explain generalization and specialization
● Implement inheritance
● Access elements of classes in inheritance
Lesson: Implementing Inheritance
© Copyright . All rights reserved. 139
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 152/505
Unit 3Lesson 2
132Implementing Up-Casts Using Inheritance
LESSON OVERVIEWThis lesson explains the concept of up-casts and dynamic and static type of referencevariable. This lesson also explains the method of implementing up-casts.
Business Example
As a developer, you must implement up-casts for an object of an airplane class. For thisreason, you require the following knowledge:
● An understanding of inheritance
● An understanding of up-casts
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement up-casts using inheritance
The Up-Cast
Figure 70: Up-Cast (Widening Cast) with Object References
You cannot portray some relationships well in static diagrams. At this point, it isrecommended that you draw the following diagram by hand and hide the slides:
. Draw the reference variable GO_TRUCK as an example on the left.
14 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 153/505
2. Write CREATE OBJECT go_truck ... above the reference variable.
3. Draw the object display of a truck on the right and connect it to the reference variable.
4. Within this object, draw an area with a few inherited components.
5. Draw another reference variable GO_VEHICLE some distance below the first one.6. Write GO_VEHICLE = GO_TRUCK above the second reference variable and ask the
participants to tell you the contents of the second reference variable.
7. Now, it depends what you want to show with the diagram. From a technical point of view,only an address is copied, so you can draw an arrow from GO_VEHICLE to the object. Youmust ask which components are addressed with GO_VEHICLE.
In contrast, in the following graphic you want to indicate the syntactic restriction of thesecond reference variable. The only reason why you can access the inherited componentsusing the second variable is because the static type is critical for the syntax check.
If you assign a subclass reference to a superclass reference, this subclass ensures that allcomponents that you can access syntactically after the cast assignment are actually availablein the instance. The subclass always contains at least the same components as thesuperclass. After all, the name and the signature of redefined methods are identical.
User can therefore address only those methods and attributes from the subclass instancethat they can from the superclass instance.
Hint:Note that with redefined methods you execute the implementation of the
subclass using the superclass static type of reference.
In this example, after the assignment, you can only access the methods GET_MAKE,GET_COUNT, DISPLAY_ATTRIBUTES, SET_ATTRIBUTES, and ESTIMATE_FUEL of theinstance LCL_TRUCK by using the reference GO_VEHICLE.
If there are any restrictions regarding visibility, they are left unchanged. It is not possible toaccess the specific components from the class LCL_TRUCK of the instance GET_CARGO inthe example using the reference GO_VEHICLE. The view or possible access to methods istherefore narrowed or at best left unchanged. There is a switch from a view of severalcomponents to a view of a few components. Since the target variable can accept moredynamic types in comparison to the source variable, this assignment is also called wideningcast.
Lesson: Implementing Up-Casts Using Inheritance
© Copyright . All rights reserved. 141
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 154/505
Static and Dynamic Type
Figure 71: Static and Dynamic Types of References
Your demonstration program should now contain something that looks like the executableprogram SAPBC401_INH_D2. You should run your program in debugging mode.
Note:At this point, the main program is still the client of the vehicle classes. This willchange soon.
Remind participants of the benefits of narrowing cast assignments. It makes it easy to extendthe vehicle management with new specific vehicles.
At this point, we recommend having the participants do the second exercise of this lesson.Strictly speaking, the exercise assumes some knowledge that will not be taught until the nextparagraph; however, this is unlikely to cause problems because many participants havealready programmed in the manner that is required here. For these participants, thisexercise is obsolete in any case.
A reference variable always has two types at runtime: static and dynamic. In the example,LCL_VEHICLE is the static type of the variable GO_VEHICLE. Depending on the castassignment, the dynamic type is either LCL_BUS or LCL_TRUCK. In the ABAP Debugger , thedynamic type is specified in the form of the following object display.
object_id<\PROGRAM=program_name\CLASS=dynamic_type>
Unit 3: Inheritance and Casting
142 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 155/505
Note:Assignments between reference variables are possible whenever the static type ofthe target variables is more general or equal to the dynamic type of the sourcevariables.
Demonstration: How to Implement Up-Casts
To demonstrate how to implement up-casts, implement suitable parts of programSAPBC401_INH_D2.
Lesson: Implementing Up-Casts Using Inheritance
© Copyright . All rights reserved. 143
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 156/505
Unit 3: Inheritance and Casting
144 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 157/505
Unit 3Exercise 8
135Implement Up-Casts
Business Example
As a developer, your airplane management program should display the attributes of theairplane objects generically, that is, it should be open to future extensions with additionalairplane classes.
Template
SAPBC401_INH_S1
Solution
SAPBC401_INH_S2
Task 1
Buffer the airplane references in a suitable type of internal table.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the sample solution program from the previous exercise.
2. In your main program, define an internal table for buffering airplane references if you donot already have one. The row type of the internal table should be REF TO LCL_AIRPLANE.
Task 2
Display the attributes of all airplane types that were created so far.
1. Insert the references to your passenger and cargo airplanes into the internal table.
2. Program a loop through the contents of the internal table. Call the DISPLAY_ATTRIBUTESmethod every time the loop runs.
Task 3
Analyze your program.
1. Follow the program flow in the ABAP Debugger , paying special attention to the call of themethod DISPLAY_ATTRIBUTES.
2. What would happen if the method DISPLAY_ATTRIBUTES had not been redefined in thesubclasses?
© Copyright . All rights reserved. 145
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 158/505
SAPBC401_INH_S2
REPORT sapbc401_inh_s2. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. ... ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* **---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. ...ENDCLASS. "lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_planeIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROMlcl_airplane. ... ENDCLASS. "lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION DATA: go_airplane TYPE REF TOlcl_airplane, go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPEREF TO lcl_passenger_plane,
gt_airplanes TYPE TABLE OF REF TO lcl_airplane, gv_count TYPE i. START-OF-SELECTION. ******************* lcl_airplane=>display_n_o_airplanes( ).CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN'iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype =1. IF sy-subrc = 0.
APPEND go_passenger TO gt_airplanes. ENDIF. CREATE OBJECT go_cargoEXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo =533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.
APPEND go_cargo TO gt_airplanes. ENDIF.
LOOP AT gt_airplanes INTO go_airplane. go_airplane->display_attributes( ). ENDLOOP. gv_count = lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: /'Number of airplanes'(ca1), gv_count.
Unit 3: Inheritance and Casting
146 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 159/505
Unit 3Solution 8
137Implement Up-Casts
Business Example
As a developer, your airplane management program should display the attributes of theairplane objects generically, that is, it should be open to future extensions with additionalairplane classes.
Template
SAPBC401_INH_S1
Solution
SAPBC401_INH_S2
Task 1
Buffer the airplane references in a suitable type of internal table.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the sample solution program from the previous exercise.
a) Carry out this step as usual. Additional information is available in the SAP Library.
2. In your main program, define an internal table for buffering airplane references if you do
not already have one. The row type of the internal table should be REF TO LCL_AIRPLANE.a) See the source code extract from the model solution.
Task 2
Display the attributes of all airplane types that were created so far.
1. Insert the references to your passenger and cargo airplanes into the internal table.
a) See the source code extract from the model solution.
2. Program a loop through the contents of the internal table. Call the DISPLAY_ATTRIBUTES
method every time the loop runs.a) See the source code extract from the model solution.
Task 3
Analyze your program.
1. Follow the program flow in the ABAP Debugger , paying special attention to the call of themethod DISPLAY_ATTRIBUTES.
a) Carry out this step as usual. Additional information is available in the SAP Library.
© Copyright . All rights reserved. 147
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 160/505
2. What would happen if the method DISPLAY_ATTRIBUTES had not been redefined in thesubclasses?
The implementation from the superclass would be executed. Your program would notcontain polymorphism.
SAPBC401_INH_S2
REPORT sapbc401_inh_s2. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. ... ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* **---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. ...ENDCLASS. "lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_planeIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROMlcl_airplane. ... ENDCLASS. "lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION DATA: go_airplane TYPE REF TOlcl_airplane, go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPEREF TO lcl_passenger_plane,
gt_airplanes TYPE TABLE OF REF TO lcl_airplane, gv_count TYPE i. START-OF-SELECTION. ******************* lcl_airplane=>display_n_o_airplanes( ).CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN'iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype =1. IF sy-subrc = 0.
APPEND go_passenger TO gt_airplanes. ENDIF. CREATE OBJECT go_cargoEXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo =533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.
APPEND go_cargo TO gt_airplanes. ENDIF.
LOOP AT gt_airplanes INTO go_airplane. go_airplane->display_attributes( ).
ENDLOOP. gv_count = lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: /
Unit 3: Inheritance and Casting
148 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 161/505
'Number of airplanes'(ca1), gv_count.
Lesson: Implementing Up-Casts Using Inheritance
© Copyright . All rights reserved. 149
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 162/505
LESSON SUMMARYYou should now be able to:
● Implement up-casts using inheritance
Unit 3: Inheritance and Casting
15 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 163/505
Unit 3Lesson 3
141Implementing Polymorphism Using Inheritance
LESSON OVERVIEWThis lesson explains the method of implementing polymorphism using inheritance.
As a developer, you need to create class and then transfer some airplane references to theairline instance. For this reason, you require the following knowledge:
● An understanding of polymorphism
● An understanding of how to implement polymorphism
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain polymorphism
● Implement polymorphism using inheritance
Generic Access
Figure 72: Generic Access After Up-Cast Assignments
A typical use for up-cast assignments is to prepare for generic access. A user who is not at allinterested in the finer points of the instances of the subclasses but who simply wants toaddress the shared components could use a superclass reference for this access.
In the example shown here, a travel agency LCL_RENTAL needs to manage all imaginablekinds of vehicles in one list. This leads to the question of what type should be assigned to the
internal table for the references to airplane instances. You should also assume that the carrental company needs to be able to calculate only the required amount of fuel for all its
© Copyright . All rights reserved. 151
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 164/505
vehicles. Correspondingly, the DISPLAY_ATTRIBUTES method is defined in the superclassLCL_VEHICLE and is redefined in all subclasses.
Row Type of the Internal Table in the Application – Example
Figure 73: Row Type of the Internal Table in the Application – Example
When objects of different classes, which are LCL_BUS, LCL_TRUCK, and LCL_CAR, in theexample are specified as type superclass references which is LCL_VEHICLE, they can bestored in an internal table. The shared components of the subclass objects can then beaccessed uniformly. For this example, therefore you need the method ADD_VEHICLE. Thiscopies the references to the vehicle types in this internal table holding the references whileup-casting. Its import parameter is already typed as the reference to the superclass.
Up-Cast and Generic Access in the Application – Example
Figure 74: Up-Cast and Generic Access in the Application – Example
In this example, the up-cast assignment occurs when the vehicle reference is transferred tothe formal parameter of the ADD_VEHICLE method. The shared component is genericallyaccessed within the loop around the internal table containing all of the vehicle references. The
Unit 3: Inheritance and Casting
152 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 165/505
DISPLAY_ATTRIBUTES method was inherited from the LCL_VEHICLE superclass and mayhave been redefined.
Polymorphism
Figure 75: Polymorphism – Generic Access Using the Superclass Reference
The runtime identifies which implementation is executed. Which DISPLAY_ATTRIBUTES iscalled depends on which object the superclass reference GO_VEHICLE currently refers to.The dynamic type and not the static type of the reference variable is used to search for theimplementation of a method. Therefore, whengo_vehicle->display_attributes iscalled, the implementation is not executed from LCL_VEHICLE which is static type ofGO_VEHICLE because the method was redefined in all vehicle classes.
When an instance receives a message to execute a particular method, the method thatimplemented the class of this instance is executed. If the class has not been redefined in themethod, the implementation from the superclass is executed.
Aspects of Polymorphism
When objects from different classes react differently to the same method calls, this is knownas polymorphism. The possibility of polymorphism is one of the main strengths of inheritance.A client can handle different classes uniformly, irrespective of their implementation. Theruntime system searches for the right implementation of a method on behalf of the client.
Polymorphism can be used to write programs that are highly generic, that is, they do not needto be changed significantly if use cases are added. For instance, this would make it very easyto add motorbikes to this example. You would simply have to define a new subclass ofLCL_VEHICLE, which you could call LCL_MOTORBIKE. You would also have to redefine theinherited method DISPLAY_ATTRIBUTES. Without needing any more changes, your vehiclemanagement system could then work with motorbikes and calculate the required fuel levelsfor them.
Lesson: Implementing Polymorphism Using Inheritance
© Copyright . All rights reserved. 153
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 166/505
Generic Calls in the Procedural Programming Model
Figure 76: Generic Calls in the Procedural Programming Model
Your demonstration program should now look somewhat like the executable programSAPBC401_INH_D3.
At this point, we recommend that the participants do the third exercise of this lesson.
Using dynamic function module calls, you can program generically in ABAP, even without anobject-oriented programming model. When you compare with polymorphism throughinheritance, it means that the source code is less self-explanatory and is more susceptible toerrors. For example, the syntax check can only check that the function model is calledcorrectly or not. But the syntax check cannot check whether the internal table contains a validfunction module name for each vehicle or not.
Demonstration: How to Implement Polymorphism
To demonstrate how to implement polymorphism, implement suitable parts of programSAPBC401_INH_D3.
Unit 3: Inheritance and Casting
154 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 167/505
Unit 3Exercise 9
145Implement Polymorphism Using Inheritance
Business Example
Now, the management of airplane instances should no longer take place in the main program.Instead, it should be encapsulated in a new class for airlines.
Template
SAPBC401_INH_S1
Solution
SAPBC401_INH_S2
Task 1
Define a local class for airlines.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the template program.
If you copy the template program then you can go directly to the next step. Otherwise,copy the local class LCL_CARRIER along with the definition and implementation of theclass from the template program and paste it into your own program.
2. Define a private instance attribute MT_AIRPLANES to store references to airplanes.3. Define and implement a public method ADD_AIRPLANE so that airplane references can be
added to the previously defined list MT_AIRPLANES. The method should have one importparameter that is IO_PLANE.
4. Define and implement a private instance method DISPLAY_AIRPLANES. In this method,loop at the list of airplanes and call method DISPLAY_ATTRIBUTES for each airplane.
Task 2
In the main program, create an airline instance. Transfer some airplane references to theairline instance and display the attributes.
1. Remove all the statements from the main program that define the global internal table forairplane references and their insertions.
2. In the main program, define a suitably typed reference variable for your new airline class.
3. Using the reference, generate an instance of your class LCL_CARRIER.
Decide for yourself how to fill the attributes.
4. Call the method ADD_AIRPLANE to transfer each airplane instance to the carrier. You mayalso create and transfer additional airplanes.
5. Display the attributes of the airline by calling its method DISPLAY_ATTRIBUTES.
© Copyright . All rights reserved. 155
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 168/505
SAPBC401_INH_S3
REPORT sapbc401_inh_s3. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. ... ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. ...ENDCLASS. "lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_planeIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROMlcl_airplane. ... ENDCLASS. "lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION*---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string, display_attributes,
add_airplane IMPORTING io_plane TYPE REF TO lcl_airplane. PRIVATE SECTION. DATA: mv_name TYPE string,
mt_airplanes TYPE TABLE OF REF TO lcl_airplane.
METHODS: display_airplanes. ENDCLASS. "lcl_carrier DEFINITION*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION*---------------------------------------------------------------------
* CLASS lcl_carrier IMPLEMENTATION. METHOD constructor. mv_name =iv_name. ENDMETHOD. "constructor METHOD display_attributes. SKIP 2.WRITE: icon_flight AS ICON, mv_name. ULINE. ULINE.
me->display_airplanes( ). ENDMETHOD. "display_attributes
METHOD add_airplane. APPEND io_plane TO mt_airplanes. ENDMETHOD. "add_airplane
METHOD display_airplanes. DATA: lo_plane TYPE REF TO lcl_airplane. LOOP AT mt_airplanes INTO lo_plane. lo_plane->display_attributes( ).
ENDLOOP. ENDMETHOD. "display_airplanes
Unit 3: Inheritance and Casting
156 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 169/505
ENDCLASS. "lcl_carrier IMPLEMENTATION DATA: go_carrier TYPE REF TO lcl_carrier, go_airplane TYPE REF TO lcl_airplane,
go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPE REF TOlcl_passenger_plane, gv_count TYPE i. START-OF-SELECTION.*******************
***** Create Carrier ****************************************** CREATE OBJECT go_carrier EXPORTING
iv_name = 'Smile&Fly-Travel;'. ***** Passenger Plane *****************************************CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN'iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype =1. IF sy-subrc = 0.
go_carrier->add_airplane( go_passenger ). ENDIF. ***** cargo Plane********************************************* CREATE OBJECT go_cargoEXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo =533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.
go_carrier->add_airplane( go_cargo ). ENDIF.
***** output carrier (including list of airplanes) ************ go_carrier->display_attributes( ).
Lesson: Implementing Polymorphism Using Inheritance
© Copyright . All rights reserved. 157
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 170/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 171/505
a) See the source code extract from the model solution.
2. In the main program, define a suitably typed reference variable for your new airline class.
a) See the source code extract from the model solution.
3. Using the reference, generate an instance of your class LCL_CARRIER.
Decide for yourself how to fill the attributes.a) See the source code extract from the model solution.
4. Call the method ADD_AIRPLANE to transfer each airplane instance to the carrier. You mayalso create and transfer additional airplanes.
a) See the source code extract from the model solution.
5. Display the attributes of the airline by calling its method DISPLAY_ATTRIBUTES.
a) See the source code extract from the model solution.
SAPBC401_INH_S3
REPORT sapbc401_inh_s3. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. ... ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. ...ENDCLASS. "lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_planeIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROMlcl_airplane. ... ENDCLASS. "lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION*---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string, display_attributes,
add_airplane IMPORTING io_plane TYPE REF TO lcl_airplane. PRIVATE SECTION. DATA: mv_name TYPE string,
mt_airplanes TYPE TABLE OF REF TO lcl_airplane.
METHODS:
display_airplanes. ENDCLASS. "lcl_carrier DEFINITION
Lesson: Implementing Polymorphism Using Inheritance
© Copyright . All rights reserved. 159
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 172/505
*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD constructor. mv_name =iv_name. ENDMETHOD. "constructor METHOD display_attributes. SKIP 2.WRITE: icon_flight AS ICON, mv_name. ULINE. ULINE.
me->display_airplanes( ). ENDMETHOD. "display_attributes
METHOD add_airplane. APPEND io_plane TO mt_airplanes. ENDMETHOD. "add_airplane
METHOD display_airplanes. DATA: lo_plane TYPE REF TO lcl_airplane. LOOP AT mt_airplanes INTO lo_plane. lo_plane->display_attributes( ). ENDLOOP. ENDMETHOD. "display_airplanes ENDCLASS. "lcl_carrier IMPLEMENTATION DATA: go_carrier TYPE REF TO lcl_carrier, go_airplane TYPE REF TO lcl_airplane,
go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPE REF TOlcl_passenger_plane, gv_count TYPE i. START-OF-SELECTION.*******************
***** Create Carrier ****************************************** CREATE OBJECT go_carrier EXPORTING
iv_name = 'Smile&Fly-Travel;'. ***** Passenger Plane *****************************************CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN'iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype =1. IF sy-subrc = 0.
go_carrier->add_airplane( go_passenger ). ENDIF. ***** cargo Plane********************************************* CREATE OBJECT go_cargoEXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo =533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.
go_carrier->add_airplane( go_cargo ). ENDIF.
***** output carrier (including list of airplanes) ************ go_carrier->display_attributes( ).
Unit 3: Inheritance and Casting
16 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 173/505
LESSON SUMMARYYou should now be able to:
● Explain polymorphism
● Implement polymorphism using inheritance
Lesson: Implementing Polymorphism Using Inheritance
© Copyright . All rights reserved. 161
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 174/505
Unit 3Lesson 4
152Implementing Down-Casts Using Inheritance
LESSON OVERVIEWThis lesson explains the method to create down-cast assignments (narrowing cast).
As in the last lesson, the theory presented should also be applied in a demonstrationprogram. It is recommended that you start using the term signature at this point or earlier inthe course, to refer to the parameters of a method. The term interface is used to meanseveral different things. Avoid using the term henceforth.
Caution:When this course was revised, the use of the terms up-cast and down-castwas changed and adapted to the current documentation (up-cast = WideningCast and down-cast = Narrowing Cast). Notify the participants of this at theend of the unit.
Business Example
As a developer, you need to create a subclass from the airplane class and then use casting toaccess different attributes. For this reason, you require the following knowledge:
● Down-casts
● Inheritance
● Implementing down-casts using Inheritance
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement down-casts using inheritance
● Model class hierarchies
162 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 175/505
The Down-Cast
Figure 77: Down-Cast (Narrowing-Cast) with Object References
At this point, we recommend that you add to your up-cast diagram and hide the slides:
● Draw another reference variable called GO_TRUCK2 under GO_VEHICLE.
● Write GO_TRUCK2 ?= GO_VEHICLE above the third reference variable and discuss withthe participants the need to use ”?”. Then ask the participants what the content of thethird reference variable is.
● Draw an arrow from GO_TRUCK2 to the object.
Ask which components can be addressed with GO_TRUCK2.
Variables of the type reference to superclass can also refer to subclass instances at runtime.You may now want to copy such a reference back to a suitable variable of the reference tosubclass type.
If you want to assign a superclass reference to a subclass reference, you must use the down-cast assignment operator MOVE ... ?TO ... or its short form ?= . Otherwise, you will get amessage stating that it is not certain that all the components that can be accessedsyntactically after the cast assignment are actually available in the instance. As a rule, thesubclass class contains more components than the superclass.
After assigning this type of reference back to a subclass reference to the implementing class,clients are no longer limited to inherited components. In the example given here, all thecomponents of the LCL_TRUCK instance can be accessed again after the assignment usingthe GO_TRUCK2 reference.
The view is thus usually widened or at least unchanged. This type of assignment of referencevariables is known as down-cast. There is a switch from a view of a few components to a viewof more components. As the target variable can accept less dynamic types after theassignment, this assignment is also called narrowing cast.
Lesson: Implementing Down-Casts Using Inheritance
© Copyright . All rights reserved. 163
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 176/505
Specific Access After Down-Cast Assignments
Figure 78: Specific Access After Down-Cast Assignments
A typical use for down-cast assignments is when you need to address specific components ofinstances and keep their references in variables that are typed on the superclass. A user whois interested in the finer points of the instances of a subclass cannot use the superclassreference for this access because it allows access only to the shared components.
Exceptions Handling for Down-Casts
Figure 79: Down-Cast and Exception Handling in the Application Example
It is recommended that you do a separate demonstration to show the need to identify theexception.
Unit 3: Inheritance and Casting
164 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 177/505
Note:Refer to the specific lesson about the exception concept. You do not haveenough time to discuss this topic now.
In this example, a car rental company (LCL_RENTAL) wants to determine the maximumcapacity of its trucks, but it stores all types of vehicle references in an internal tableLCL_VEHICLE. What happens if there is no truck reference in the GO_VEHICLE superclassreference at runtime but the down-cast assignment operator tries to copy the reference tothe now invalid reference GO_TRUCK?
In contrast to the up-cast assignment, it is possible that the static type of the target variable(GO_TRUCK) is neither more general than nor the same as the dynamic type of the sourcevariable (GO_VEHICLE), namely when GO_VEHICLE contains bus or sports car references.That is the reason why with this kind of cast, the runtime system checks before the
assignment whether the current content of the source variable corresponds to the typerequirements of the target variable. Otherwise, an exception that can be handled is triggeredand the original value of the target variable remains the same.
You can identify this exception of the error class CX_SY_MOVE_CAST_ERROR using TRY-ENDTRY and the CATCH statement. Another way of preventing this runtime error is to useruntime type identification (RTTI) classes. You can use RTTI classes to determine thedynamic type at runtime and set a condition for the cast.
Demonstration: How to Implement Down-Casts
To demonstrate how to implement down-casts, implement suitable parts of theSAPBC401_INH_D3 program.
Lesson: Implementing Down-Casts Using Inheritance
© Copyright . All rights reserved. 165
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 178/505
Unit 3: Inheritance and Casting
166 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 179/505
Unit 3Exercise 10
155Implement Down-Casts
Business Example
As a developer, design an application where you want to know about the highest cargo load ofthe airplane without knowing the details.
Template:
SAPBC401_INH_T3
Solution:
SAPBC401_INH_S3_OPT (Task 3)
Define the highest cargo value.
1. In the LCL_CARGO_PLANE class, define and implement the GET_CARGO public functionalmethod to return the cargo value. Define a returning parameter RV_CARGO.
2. In the LCL_CARRIER class, define and implement the GET_MAX_CARGO private functionmethod to calculate the highest cargo value (load capacity) of all cargo planes. Loop at thelist of airplanes and use the down-cast technique to identify cargo planes. For thoseairplanes for which the down-cast was successful, you can then call the GET_CARGO
method defined and implemented in the previous step.3. Call the GET_MAX_CARGO method from within the DISPLAY_ATTRIBUTES method class
LCL_CARRIER and output the result.
© Copyright . All rights reserved. 167
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 180/505
Unit 3Solution 10
156Implement Down-Casts
Business Example
As a developer, design an application where you want to know about the highest cargo load ofthe airplane without knowing the details.
Template:
SAPBC401_INH_T3
Solution:
SAPBC401_INH_S3_OPT (Task 3)
Define the highest cargo value.
1. In the LCL_CARGO_PLANE class, define and implement the GET_CARGO public functionalmethod to return the cargo value. Define a returning parameter RV_CARGO.
a) See the source code extract from the model solution.
2. In the LCL_CARRIER class, define and implement the GET_MAX_CARGO private functionmethod to calculate the highest cargo value (load capacity) of all cargo planes. Loop at thelist of airplanes and use the down-cast technique to identify cargo planes. For those
airplanes for which the down-cast was successful, you can then call the GET_CARGOmethod defined and implemented in the previous step.
a) See the source code extract from the model solution.
3. Call the GET_MAX_CARGO method from within the DISPLAY_ATTRIBUTES method classLCL_CARRIER and output the result.
a) See the source code extract from the model solution.
SAPBC401_INH_S3
REPORT sapbc401_inh_s3_opt.
TYPE-POOLS icon....
*---------------------------------------------------------------------** CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------***---------------------------------------------------------------------*CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
168 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 181/505
PUBLIC SECTION.
METHODS: constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype
iv_cargo TYPE s_plan_car EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION,
get_cargo RETURNING value(rv_cargo) TYPE s_plan_car.
PRIVATE SECTION.
DATA: mv_cargo TYPE s_plan_car.
ENDCLASS. "lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------** CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------*CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor. super->constructor( EXPORTING iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF. mv_cargo = iv_cargo. ENDMETHOD. "constructor
METHOD display_attributes. super->display_attributes( ). WRITE:
/ 'Max Cargo:'(005), AT c_pos_1 mv_cargo LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributes
METHOD get_cargo. rv_cargo = mv_cargo. ENDMETHOD. "get_cargo
ENDCLASS. "lcl_cargo_plane IMPLEMENTATION
...
Lesson: Implementing Down-Casts Using Inheritance
© Copyright . All rights reserved. 169
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 182/505
*---------------------------------------------------------------------** CLASS lcl_carrier DEFINITION*---------------------------------------------------------------------*CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
METHODS: constructor IMPORTING iv_name TYPE string,
display_attributes,
add_airplane IMPORTING io_plane TYPE REF TO lcl_airplane.
PRIVATE SECTION.
DATA: mv_name TYPE string,
mt_airplanes TYPE TABLE OF REF TO lcl_airplane. METHODS: display_airplanes,
get_max_cargo RETURNING value(rv_max_cargo) TYPE s_plan_car.
ENDCLASS. "lcl_carrier DEFINITION
*---------------------------------------------------------------------** CLASS lcl_carrier IMPLEMENTATION*---------------------------------------------------------------------*CLASS lcl_carrier IMPLEMENTATION.
METHOD constructor. mv_name = iv_name. ENDMETHOD. "constructor
METHOD display_attributes.
DATA: lv_max_cargo TYPE s_plan_car.
SKIP 2.
WRITE: icon_flight AS ICON, mv_name. ULINE. ULINE. me->display_airplanes( ).
lv_max_cargo = me->get_max_cargo( ). WRITE: / 'Capacity of biggest cargo plane:'(max), lv_max_cargo LEFT-JUSTIFIED.
ENDMETHOD. "display_attributes
Unit 3: Inheritance and Casting
17 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 183/505
METHOD add_airplane. APPEND io_plane TO mt_airplanes. ENDMETHOD. "add_airplane
METHOD display_airplanes. DATA: lo_plane TYPE REF TO lcl_airplane.
LOOP AT mt_airplanes INTO lo_plane. lo_plane->display_attributes( ). ENDLOOP. ENDMETHOD. "display_airplanes
METHOD get_max_cargo. DATA: lo_plane TYPE REF TO lcl_airplane, lo_cargo TYPE REF TO lcl_cargo_plane.
LOOP AT mt_airplanes INTO lo_plane.
TRY. lo_cargo ?= lo_plane.
IF rv_max_cargo < lo_cargo->get_cargo( ). rv_max_cargo = lo_cargo->get_cargo( ). ENDIF.
CATCH cx_sy_move_cast_error.* plane is not a cargo plane - do nothing ENDTRY. ENDLOOP. ENDMETHOD. "get_max_cargo
ENDCLASS. "lcl_carrier IMPLEMENTATION
Lesson: Implementing Down-Casts Using Inheritance
© Copyright . All rights reserved. 171
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 184/505
Correct Usage of Class Hierarchies
Figure 80: Usage of Class Hierarchies
This final section does not examine whether or not inheritance should be used as aprogramming technique over a number of alternatives. As early as the modeling phase, youshould be able to see whether there is a generalization/specialization relationship betweencertain classes. If there is, you can use inheritance to represent this in ABAP Objects.
If this is the case, you need to adhere to the relevant concepts of inheritance. For example, thesemantics must be preserved when you redefine methods. Furthermore, you must useinherited components as intended in the superclass.
Misuse of Inheritance
Figure 81: Examples – Misuse of Inheritance
If you do not have a correct understanding of the formulation “is a (specific)”, you run the riskof identifying the wrong places in which to use inheritance. Sometimes the need for anotherattribute for a class is incorrectly answered with a specialization.
For example, a superclass called Car contains the subclasses Red Car, Blue Car, and so on.The statement “A red car is a specific car” is correct only at first glance. However, there areno cars without a color. At most, there are some cars that have not been painted. Therefore,every car needs the attribute Color, assuming that it is relevant to the application. Therefore,the attribute should already have been defined in the superclass or there is no longer anauthorization for subclasses of this type. There will also be contradictions with reality whenyou try to implement a method for painting the cars.
Unit 3: Inheritance and Casting
172 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 185/505
Note:Such attributes are often also defined as reference variables to a superclass ofrole classes. There is one description class for each role. To change the role of aninstance, you then exchange the references to the corresponding role description
instances. Specialist literature also refers to this as a role design pattern.
In some cases, specialization relationships that do not allow for the semantics to be preservedare identified.
For example, the Square class inherits from the Rectangle class. If you try to define methodsfor the rectangle that change the width and height separately, these methods will not makesense when applied to the square. Even if the methods are redefined to make the lengths ofthe sides uniform, the semantics will be different.
For the same reason, simple inheritance of the source text, which means using inheritanceonly because some required functions are found in a super class, is also impossible.
What are the advantages of correctly using class hierarchies?
X A Centralized maintenance
X B Safe and generic method of access
X C Semantics preserved
X D Intended use of inherited components
Lesson: Implementing Down-Casts Using Inheritance
© Copyright . All rights reserved. 173
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 186/505
LESSON SUMMARYYou should now be able to:
● Implement down-casts using inheritance
● Model class hierarchies
Unit 3: Inheritance and Casting
174 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 187/505
Unit 3
163Learning Assessment
1. Which of the following is a relationship in which the subclass inherits all the maincharacteristics of the superclass?
Choose the correct answers.
X A Specialization
X B Generalization
X C Polymorphism
X D Casting
2. Which of the following are the characteristics of generalization or specialization?
Choose the correct answers.
X A Common components only exist once in the superclass
X B Components in the subclasses are available in all superclasses
X C Subclasses contain extensions or changes
X D Subclasses are not dependent on superclasses
3. Which of the following can be called automatically in the superclass?
Choose the correct answers.
X A Method
X B Instance constructor
X C Static constructor
X D Object
4. A superclass is a generalization of its subclasses.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 175
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 188/505
5. Which of the following section is used to change superclasses without the need to knowthe subclasses?
Choose the correct answers.
X A PROTECTED
X B PRIVATE
X C PUBLIC
6. A __________ can always have a static constructor.
Choose the correct answer.
X A subclass
X B superclass
X C subclass and superclass
7. Which of the following is used to define the static type of reference variable?
Choose the correct answer.
X A APPEND
X B CREATE OBJECT
X C TYPE REF TO
X D CLASS
8. Which of the following is determined by the assignment?
Choose the correct answer.
X A Superclasses
X B Static type
X C Dynamic type
X D Subclasses
Unit 3: Learning Assessment
176 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 189/505
9. Suppose that you have a class X that inherits from class Y. After an up-cast a referencevariable that is statically typed TYPE REF TO Y points to an instance of class X. Whatcomponents of class X can you access with this reference variable?
Choose the correct answers.
X A Components defined in class X
X B Components inherited from class Y
X C Components redefined in class X
X D Components defined in class X and redefined in its subclasses
10. When objects from different classes react differently to the same method calls, this isknown as __________.
Choose the correct answer.
X A objects
X B events
X C polymorphism
X D inheritance
11. A typical use for ________ assignments is to prepare for generic access.
Choose the correct answer.
X A events
X B up-cast
X C methods
X D down-cast
12. Which of the following is used to assign a superclass reference to a subclass reference?
Choose the correct answer.
X A Widening Cast
X B Narrowing Cast
X C Redefinition
Unit 3: Learning Assessment
© Copyright . All rights reserved. 177
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 190/505
13. Which of the following is the down-cast assignment operator?
Choose the correct answer.
X A APPEND
X B CATCH
X C MOVE ... ?TO ...
X D TRY-ENDTRY
14. Suppose you have the same class X that inherits from class Y. After a down-cast, areference variable that statically typed TYPE REF TO X points to an instance of class X.Which of the following components of class X can you access with this reference variable?
Choose the correct answers.
X A Components defined in class X
X B Components inherited from class Y
X C Components redefined in class X
X D Components defined in class X and redefined in its subclasses
X E Components inherited and redefined from a ‘Friend’ relationship
15. Suppose a reference variable that is typed on an interface contains an instance referenceof a class that implements this interface and you copy this to a reference variable that istyped on the class (down-cast). Which of the following components can you access withthis reference variable?
Choose the correct answers.
X A The components of the interface
X B The components from the class that are not defined on the interface
X C All components of the class
X D The components of the interface for which alias names have been defined
X E Components from a ‘Friend’ relationship
Unit 3: Learning Assessment
178 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 191/505
16. What are the advantages of correctly using class hierarchies?
Choose the correct answers.
X A Centralized maintenance
X B Safe and generic method of access
X C Semantics preserved
X D Intended use of inherited components
Unit 3: Learning Assessment
© Copyright . All rights reserved. 179
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 192/505
Unit 3
168Learning Assessment- Answers
1. Which of the following is a relationship in which the subclass inherits all the maincharacteristics of the superclass?
Choose the correct answers.
X A Specialization
X B Generalization
X C Polymorphism
X D Casting
2. Which of the following are the characteristics of generalization or specialization?
Choose the correct answers.
X A Common components only exist once in the superclass
X B Components in the subclasses are available in all superclasses
X C Subclasses contain extensions or changes
X D Subclasses are not dependent on superclasses
3. Which of the following can be called automatically in the superclass?
Choose the correct answers.
X A Method
X B Instance constructor
X C Static constructor
X D Object
18 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 193/505
4. A superclass is a generalization of its subclasses.
Determine whether this statement is true or false.
X True
X False
5. Which of the following section is used to change superclasses without the need to knowthe subclasses?
Choose the correct answers.
X A PROTECTED
X B PRIVATE
X C PUBLIC
6. A __________ can always have a static constructor.
Choose the correct answer.
X A subclass
X B superclass
X C subclass and superclass
7. Which of the following is used to define the static type of reference variable?
Choose the correct answer.
X A APPEND
X B CREATE OBJECT
X C TYPE REF TO
X D CLASS
Unit 3: Learning Assessment- Answers
© Copyright . All rights reserved. 181
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 194/505
8. Which of the following is determined by the assignment?
Choose the correct answer.
X A Superclasses
X B Static type
X C Dynamic type
X D Subclasses
9. Suppose that you have a class X that inherits from class Y. After an up-cast a referencevariable that is statically typed TYPE REF TO Y points to an instance of class X. Whatcomponents of class X can you access with this reference variable?
Choose the correct answers.
X A Components defined in class X
X B Components inherited from class Y
X C Components redefined in class X
X D Components defined in class X and redefined in its subclasses
10. When objects from different classes react differently to the same method calls, this isknown as __________.
Choose the correct answer.
X A objects
X B events
X C polymorphism
X D inheritance
11. A typical use for ________ assignments is to prepare for generic access.
Choose the correct answer.
X A events
X B up-cast
X C methods
X D down-cast
Unit 3: Learning Assessment- Answers
182 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 195/505
12. Which of the following is used to assign a superclass reference to a subclass reference?
Choose the correct answer.
X A Widening Cast
X B Narrowing Cast
X C Redefinition
13. Which of the following is the down-cast assignment operator?
Choose the correct answer.
X A APPEND
X B CATCH
X C MOVE ... ?TO ...
X D TRY-ENDTRY
14. Suppose you have the same class X that inherits from class Y. After a down-cast, areference variable that statically typed TYPE REF TO X points to an instance of class X.Which of the following components of class X can you access with this reference variable?
Choose the correct answers.
X A Components defined in class X
X B Components inherited from class Y
X C Components redefined in class X
X D Components defined in class X and redefined in its subclasses
X E Components inherited and redefined from a ‘Friend’ relationship
Unit 3: Learning Assessment- Answers
© Copyright . All rights reserved. 183
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 196/505
15. Suppose a reference variable that is typed on an interface contains an instance referenceof a class that implements this interface and you copy this to a reference variable that istyped on the class (down-cast). Which of the following components can you access withthis reference variable?
Choose the correct answers.
X A The components of the interface
X B The components from the class that are not defined on the interface
X C All components of the class
X D The components of the interface for which alias names have been defined
X E Components from a ‘Friend’ relationship
16. What are the advantages of correctly using class hierarchies?Choose the correct answers.
X A Centralized maintenance
X B Safe and generic method of access
X C Semantics preserved
X D Intended use of inherited components
Unit 3: Learning Assessment- Answers
184 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 197/505
UNIT 4 Interfaces and Casting
Lesson 1
Defining and Implementing Local Interfaces 186Exercise 11: Define and Implement a Local Interface 193
Lesson 2
Implement Polymorphism Using Interfaces 204
Exercise 12: Implement Polymorphism Using Interfaces 209
Lesson 3
Joining Classmodels Using Interfaces 220Exercise 13: Join Classmodels Using Interfaces 223
UNIT OBJECTIVES● Explain the usage areas for interfaces
● Create generalization/specialization relationships using interfaces
● Implement polymorphism using interfaces
● Implement down-casts with interfaces
● Join different submodels using interfaces
● Create and use interface hierarchies
© Copyright . All rights reserved. 185
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 198/505
Unit 4Lesson 1
174Defining and Implementing Local Interfaces
LESSON OVERVIEWThis lesson explains the method of defining and implementing interfaces.
Although there are no significant technical differences between regular inheritance and theimplementation of interfaces, this topic is still covered separately in this lesson. This meansyou can use the lesson without previously having explained inheritance. The areas of use forinterfaces are the most important because it deals precisely with these differences.
In this lesson, you must make a clear distinction between the terms signature and interface.Otherwise, you will confuse the participants.
Business Example
As a developer, create interfaces and implement them in different airplane classes. For thisreason, you require the following knowledge:
● An understanding of interface use
● An understanding of interface definition
●
An understanding of interface implementation
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain the usage areas for interfaces
● Create generalization/specialization relationships using interfaces
186 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 199/505
Areas of Use for Interfaces
Figure 82: Central Definition of Shared Components
Interfaces differ from regular inheritance in their areas of use. In terms of programming, thereare hardly any differences. However, from a technical point of view, interfaces are simplysuperclasses that cannot be instantiated, do not have an implementation part, and have onlypublic components. But, you can simulate multiple inheritance using interfaces.
In ABAP Objects, interfaces primarily serve to define uniform interface protocols for services.Various classes can implement these services in different ways, but you need to keep thesame semantics. Interfaces therefore contain no implementations.
In ABAP Objects, the same components can generally be defined in interfaces and classes. Torecognize the semantic differences from regular inheritance, you can concentrate on thefollowing typical use cases.
For example, you want to allow the option of having multiple classes implement a service indifferent ways but using the same method names and a uniform signature. With regularinheritance, you would define such a method in the shared superclass. However, if you cannotmodel a superclass suitably for inheritance, you need to define an interface and then definethe method in the interface. Therefore, you can compare this case with a generalizationrelationship within a superclass.
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 187
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 200/505
Protocol Definition by Client
Figure 83: Client Defines The Protocoll
Compared to regular inheritance, the distribution of roles is sometimes different. The usergenerally defines the interfaces. In these interfaces, the user describes both technically andsemantically the services that the user wants the providers to offer. Each class can nowdecide for itself whether it serves the interface, that is, actually offers the services defined inthe interface. Therefore, this case is similar to a specialization relationship with a subclass.
As with regular inheritance, access to these services defined in the interface is then usuallygeneric, that is, it uses a reference that is typed on the interface. As with regular inheritance,
you can thus perform polymorphism with interfaces.
Generic Access to Interface Components
Figure 84: Interfaces in UML Notation
In Unified Modeling Language (UML), you represent the interfaces in the same way as classes.
However, in addition to the interface’s name, UML have the stereotype «interface» . You
Unit 4: Interfaces and Casting
188 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 201/505
represent the use of an interface by a dotted line with a two-sided arrow from the user to theinterface; the stereotype «uses» is optional.
Definition and Implementation of Interfaces
Figure 85: Defining and Implementing an Interface
Before adding the definition of an interface to your program, it is recommended that you firstdemonstrate how to move the class definitions and implementations to an include program.Mention that this is done to make the main program is easy to read.
Make sure you emphasize that nowadays include programs should be used only by one mainprogram. In particular, include programs must not be used to make local class definitionsand implementations reusable. Hint at the global classes that should be used instead, whichwill be discussed in the next lesson.
Only then add the definition of the interface in a separate include program and implement itin your car rental class. Point out that you will use the interface only at a later stage. Now letthe participants do the first exercise.
In ABAP Objects, you can define the same components in an interface as in classes. However,interfaces do not know the visibility levels of components, that is, all the components of an
interface are public.Classes implement interfaces in the following ways:● The interface name is listed in the definition part of the class with the INTERFACES
statement. This must be in the PUBLIC SECTION, that is, interfaces can only beimplemented publicly.
● The interface methods must be implemented in the implementation part of the class.
● The components defined in the interface can be addressed in the implementation part ofthe class.
Interface components are distinguished from the other components in the implementing
class by prefixing the interface name followed by a tilde (~) which is the interface resolutionoperator.
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 189
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 202/505
interface_name~component_name
To simplify access to interface components, you can use alias names. These alias names canappear only in the definition part of a class or in the interface definition. The use of aliasnames is subject to the visibility restriction of the defining class.
An alias for an interface method is as follows:
ALIASES a_1 FOR lif_1~method_1 .
The interface method lif_1~method_1 can then be addressed with the shorter form ref->a_1 .
Access to Interface Components
Figure 86: Addressing Interface Components Using Object References
In your demonstration program, replace the call of the DISPLAY_ATTRIBUTES method ofLCL_RENTAL by a call of the LIF_PARTNER~DISPLAY_PARTNER method. Yourdemonstration program should now resemble the main program, SAPBC401_INT_D1.
Point out that you rarely use this way to access interface components. At this point, thecompleteness of the explanation is what matters. The demonstration shows how you actuallywork with interfaces.
At this point, we recommend having the participants do the first exercise of this lesson.
You can access interface components only by using an object reference whose classimplements the interface. Syntactically, this takes place with the interface resolution operator(~), just as with access to the interface components in the implementation part of the class.
Alternatively, you can use the alias names defined in the implementing class for the interfacecomponents. Even if shared components of the implementing classes are subsequentlytransferred to the interface, access to these components does not need to be adapted.However, the source code will then be less self-explanatory because you can conclude fromthe syntax that the components were defined in the class.
Unit 4: Interfaces and Casting
19 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 203/505
Demonstration: How to Define and Implement a Local Interface
To demonstrate how to define and implement a local interface, implement suitable parts ofprogram SAPBC401_INT_D1.
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 191
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 204/505
Unit 4: Interfaces and Casting
192 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 205/505
Unit 4Exercise 11
179Define and Implement a Local Interface
Please note that this is the most difficult exercise in the course for those not familiar withobject-oriented programming. The topic is relatively abstract and hard to grasp for thebeginners and weaker participants; it is perhaps the most important exercise in the coursebecause everything that has been learnt so far is consolidated again in a larger, moreextensive programming exercise.
Caution:● This is where you should consider your exact teaching method in advance.
● It will be best to carry out the individual sub exercise step by step.
● Motivate your participants with questions about the aims and objectives ofthe individual steps.
Business Example
You want to add a car rental company to your program. The car rental company together withthe existing airline should then be aggregated by a travel agency class as the travel agency’sbusiness partners. For this aggregation, you need a generic access to airlines and car rentalcompanies. Instead of defining a common superclass, you decide to define an interface withgeneric services, which is then implemented in the classes for airlines and car rentalcompanies.
In this exercise, you define and implement the interface in your existing class for airlines.
Template:
SAPBC401_INH_S3
Solution:
SAPBC401_INT_S1
Task 1
In order to increase the legibility of your program, first split the source code into a mainprogram and one include program.
The include program should contain all the local class definitions and implementations; thedeclaration of reference variables and the START-OF-SELECTION event block should remainin the main program.
© Copyright . All rights reserved. 193
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 206/505
Note:This distribution is not according to the recommended use of includes in ABAPprograms. According to the programming guidelines, the class definitions anddata declarations should go to the TOP-include, the implementations to a P-
include, and the START-OF-SELECTION event block to an E-include.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe sample solution from the previous exercise.
2. In your main program, implement the usage of a new include program (recommendedname: ZBC401_##_CARRIER with ## being your two-digit group number). Create theinclude through forward navigation. You can do this by double-clicking the include’s name.
3. Cut the definition and implementation sections of all the four local classes from the mainprogram and paste them on to the newly created include program.
4. Where do you have to place the INCLUDE statement to avoid syntax errors?
5. Activate and test your program.
Task 2
Define an interface with the DISPLAY_PARTNER method in order to later offer generic accessoptions to potential clients in the travel agency example.
1. Create a new include (recommended name: ZBC401_##_AGENCY with ## being yourtwo-digit group number) and define an interface LIF_PARTNER in the new include.
2. The interface should contain the DISPLAY_PARTNER instance method. The methodshould not have any parameters. Later on, your task will be to display business partnerattributes.
Check the entire program for syntactical correctness and activate it.
Task 3
The LCL_CARRIER class should make the services defined in the interface available topotential clients. To achieve this, class LCL_CARRIER needs to implement the interface andtherefore the interface method DISPLAY_PARTNER.
1. In the definition of LCL_CARRIER, declare the newly created interface.
2. Implement the coding of the DISPLAY_PARTNER interface method in the LCL_CARRIERclass. As is evident from the name of the method, the data or attributes of this businesspartner should be displayed here. Consider the possible solutions and execute the mostsuitable approach.
Check the entire application for syntactical correctness and activate your application.
Unit 4: Interfaces and Casting
194 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 207/505
Hint:The performance of the application will still not change at this point; theresults can be seen only in the later tasks.
Task 4
Test the interface implemented in the LCL_CARRIER class by calling the interface methodfrom the main program.
1. In the main program, remove the call of the DISPLAY_ATTRIBUTES method of theLCL_CARRIER class. Replace it with a call of the DISPLAY_PARTNER interface method.
2. What would be the aim and objective of such a call at this point of the exercise be, or to putit differently, what does the option of this interface method call bring out of the mainprogram in contrast with a conventional method call?
3. After a successful test, turn this method call into a comment so that it becomesineffective.
Hint:The generic use of the interface methods using another class takes place inthe next steps of the exercise. The performance of the entire application willstill not change at this point; the results can be seen only in the later tasks.
Main program: SAPBC401_INT_S1
REPORT sapbc401_int_s1. TYPE-POOLS icon.
INCLUDE bc401_int_s1_agency.INCLUDE bc401_int_s1_carrier. DATA: go_carrier TYPE REF TO lcl_carrier, go_airplane TYPE REF TOlcl_airplane, go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPEREF TO lcl_passenger_plane, gv_count TYPE i. START-OF-SELECTION.******************* ***** Create Carrier****************************************** CREATE OBJECT go_carrierEXPORTING iv_name = 'Smile&Fly-Travel'. ***** Passenger Plane***************************************** CREATE OBJECT go_passengerEXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400' iv_seats =345 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0. go_carrier->add_airplane( go_passenger ). ENDIF. ***** cargo Plane********************************************* CREATE OBJECT go_cargoEXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo =533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0. go_carrier->add_airplane( go_cargo ). ENDIF. ***** output carrier (including listof airplanes) ************
* only for testing:* call interface method for the carrier
go_carrier->lif_partner~display_partner( ).* go_carrier->display_attributes( ).
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 195
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 208/505
Include BC401_INT_S1_AGENCY
INTERFACE lif_partner. METHODS display_partner.ENDINTERFACE.
Include BC401_INT_S1_CARRIER
*------------------------------------------------------------------** CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. ... ENDCLASS. "lcl_airplane DEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION *
*------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* **---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. ...ENDCLASS. "lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_plane
IMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROMlcl_airplane. ... ENDCLASS. "lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION*---------------------------------------------------------------------
* CLASS lcl_carrier DEFINITION. PUBLIC SECTION.
Unit 4: Interfaces and Casting
196 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 209/505
INTERFACES:
lif_partner. METHODS: constructor IMPORTING iv_name TYPE string,display_attributes, add_airplane IMPORTING io_plane TYPE REF TOlcl_airplane. PRIVATE SECTION. DATA: mv_name TYPE string, mt_airplanesTYPE TABLE OF REF TO lcl_airplane. METHODS: display_airplanes.
ENDCLASS. "lcl_carrier DEFINITION*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD constructor. mv_name =iv_name. ENDMETHOD. "constructor METHOD display_attributes. SKIP 2.WRITE: icon_flight AS ICON, mv_name. ULINE. ULINE. me->display_airplanes( ). ENDMETHOD. "display_attributes METHODadd_airplane. APPEND io_plane TO mt_airplanes. ENDMETHOD."add_airplane METHOD display_airplanes. DATA: lo_plane TYPE REF TOlcl_airplane. LOOP AT mt_airplanes INTO lo_plane. lo_plane->display_attributes( ). ENDLOOP. ENDMETHOD. "display_airplanes
METHOD lif_partner~display_partner. me->display_attributes( ). ENDMETHOD. "lif_partner~display_partner ENDCLASS. "lcl_carrier IMPLEMENTATION
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 197
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 210/505
Unit 4Solution 11
184Define and Implement a Local Interface
Please note that this is the most difficult exercise in the course for those not familiar withobject-oriented programming. The topic is relatively abstract and hard to grasp for thebeginners and weaker participants; it is perhaps the most important exercise in the coursebecause everything that has been learnt so far is consolidated again in a larger, moreextensive programming exercise.
Caution:● This is where you should consider your exact teaching method in advance.
● It will be best to carry out the individual sub exercise step by step.
● Motivate your participants with questions about the aims and objectives ofthe individual steps.
Business Example
You want to add a car rental company to your program. The car rental company together withthe existing airline should then be aggregated by a travel agency class as the travel agency’sbusiness partners. For this aggregation, you need a generic access to airlines and car rentalcompanies. Instead of defining a common superclass, you decide to define an interface withgeneric services, which is then implemented in the classes for airlines and car rentalcompanies.
In this exercise, you define and implement the interface in your existing class for airlines.
Template:
SAPBC401_INH_S3
Solution:
SAPBC401_INT_S1
Task 1
In order to increase the legibility of your program, first split the source code into a mainprogram and one include program.
The include program should contain all the local class definitions and implementations; thedeclaration of reference variables and the START-OF-SELECTION event block should remainin the main program.
198 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 211/505
Note:This distribution is not according to the recommended use of includes in ABAPprograms. According to the programming guidelines, the class definitions anddata declarations should go to the TOP-include, the implementations to a P-
include, and the START-OF-SELECTION event block to an E-include.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe sample solution from the previous exercise.
a) Carry out this step in the usual manner. Additional information about the copying ofprograms is available in the SAP Library.
2. In your main program, implement the usage of a new include program (recommendedname: ZBC401_##_CARRIER with ## being your two-digit group number). Create theinclude through forward navigation. You can do this by double-clicking the include’s name.
a) See the source text excerpt from the model solution.
3. Cut the definition and implementation sections of all the four local classes from the mainprogram and paste them on to the newly created include program.
a) See the source text excerpt from the model solution.
4. Where do you have to place the INCLUDE statement to avoid syntax errors?
The INCLUDE statement has to be placed before the declaration of reference variables.Otherwise, the class definitions are not known in the declaration of reference variables.
5. Activate and test your program.
a) Carry out this step in the usual manner. Additional information about the copying ofprograms is available in the SAP Library.
Task 2
Define an interface with the DISPLAY_PARTNER method in order to later offer generic accessoptions to potential clients in the travel agency example.
1. Create a new include (recommended name: ZBC401_##_AGENCY with ## being yourtwo-digit group number) and define an interface LIF_PARTNER in the new include.
a) See the source text excerpt from the model solution.
2. The interface should contain the DISPLAY_PARTNER instance method. The methodshould not have any parameters. Later on, your task will be to display business partnerattributes.
Check the entire program for syntactical correctness and activate it.
a) See the source text excerpt from the model solution.
Task 3
The LCL_CARRIER class should make the services defined in the interface available topotential clients. To achieve this, class LCL_CARRIER needs to implement the interface andtherefore the interface method DISPLAY_PARTNER.
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 199
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 212/505
1. In the definition of LCL_CARRIER, declare the newly created interface.
a) See the source text excerpt from the model solution.
2. Implement the coding of the DISPLAY_PARTNER interface method in the LCL_CARRIERclass. As is evident from the name of the method, the data or attributes of this businesspartner should be displayed here. Consider the possible solutions and execute the most
suitable approach.Check the entire application for syntactical correctness and activate your application.
Hint:The performance of the application will still not change at this point; theresults can be seen only in the later tasks.
a) See the source text excerpt from the model solution.
Task 4
Test the interface implemented in the LCL_CARRIER class by calling the interface methodfrom the main program.
1. In the main program, remove the call of the DISPLAY_ATTRIBUTES method of theLCL_CARRIER class. Replace it with a call of the DISPLAY_PARTNER interface method.
a) See the source text excerpt from the model solution.
2. What would be the aim and objective of such a call at this point of the exercise be, or to putit differently, what does the option of this interface method call bring out of the mainprogram in contrast with a conventional method call?
Apart from the detailed and longer syntax of this call, the interface method’s call can bereplaced by an ordinary instance method call from, for example, DISPLAY_ATTRIBUTES.At this point in the exercise, this call does not seem altogether sensible.
3. After a successful test, turn this method call into a comment so that it becomesineffective.
Hint:The generic use of the interface methods using another class takes place inthe next steps of the exercise. The performance of the entire application will
still not change at this point; the results can be seen only in the later tasks.
a) See the source text excerpt from the model solution.
Main program: SAPBC401_INT_S1
REPORT sapbc401_int_s1. TYPE-POOLS icon.
INCLUDE bc401_int_s1_agency.INCLUDE bc401_int_s1_carrier. DATA: go_carrier TYPE REF TO lcl_carrier, go_airplane TYPE REF TOlcl_airplane, go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPEREF TO lcl_passenger_plane, gv_count TYPE i. START-OF-SELECTION.
******************* ***** Create Carrier****************************************** CREATE OBJECT go_carrier
Unit 4: Interfaces and Casting
2 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 213/505
EXPORTING iv_name = 'Smile&Fly-Travel'. ***** Passenger Plane***************************************** CREATE OBJECT go_passengerEXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400' iv_seats =345 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0. go_carrier->add_airplane( go_passenger ). ENDIF. ***** cargo Plane********************************************* CREATE OBJECT go_cargoEXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo =
533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0. go_carrier->add_airplane( go_cargo ). ENDIF. ***** output carrier (including listof airplanes) ************
* only for testing:* call interface method for the carrier
go_carrier->lif_partner~display_partner( ).* go_carrier->display_attributes( ).
Include BC401_INT_S1_AGENCY
INTERFACE lif_partner. METHODS display_partner.ENDINTERFACE.
Include BC401_INT_S1_CARRIER
*------------------------------------------------------------------** CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. ... ENDCLASS. "lcl_airplane DEFINITION
*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* **---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. ...ENDCLASS. "lcl_cargo_plane DEFINITION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION
*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_plane
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 2 1
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 214/505
IMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROMlcl_airplane. ... ENDCLASS. "lcl_passenger_plane DEFINITION*---------------------------------------------------------------------
* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION*---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION.
INTERFACES: lif_partner. METHODS: constructor IMPORTING iv_name TYPE string,display_attributes, add_airplane IMPORTING io_plane TYPE REF TO
lcl_airplane. PRIVATE SECTION. DATA: mv_name TYPE string, mt_airplanesTYPE TABLE OF REF TO lcl_airplane. METHODS: display_airplanes.ENDCLASS. "lcl_carrier DEFINITION*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD constructor. mv_name =iv_name. ENDMETHOD. "constructor METHOD display_attributes. SKIP 2.WRITE: icon_flight AS ICON, mv_name. ULINE. ULINE. me->display_airplanes( ). ENDMETHOD. "display_attributes METHODadd_airplane. APPEND io_plane TO mt_airplanes. ENDMETHOD."add_airplane METHOD display_airplanes. DATA: lo_plane TYPE REF TOlcl_airplane. LOOP AT mt_airplanes INTO lo_plane. lo_plane->display_attributes( ). ENDLOOP. ENDMETHOD. "display_airplanes
METHOD lif_partner~display_partner. me->display_attributes( ). ENDMETHOD. "lif_partner~display_partner ENDCLASS. "lcl_carrier IMPLEMENTATION
Unit 4: Interfaces and Casting
2 2 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 215/505
LESSON SUMMARYYou should now be able to:
● Explain the usage areas for interfaces
● Create generalization/specialization relationships using interfaces
Lesson: Defining and Implementing Local Interfaces
© Copyright . All rights reserved. 2 3
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 216/505
Unit 4Lesson 2
190Implement Polymorphism Using Interfaces
LESSON OVERVIEWThis lesson explains the method of defining and implementing polymorphism usinginterfaces.
Business Example
As a developer, create interfaces and implement them using polymorphism in differentairplane classes. For this reason, you require the following knowledge:
● An understanding of interfaces
● An understanding of polymorphism
● An understanding of interface implementation using polymorphism
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement polymorphism using interfaces
Polymorphism with Interfaces
Figure 87: Up-Cast with Interface References
You cannot portray some relationships well in static diagrams.
Following are the steps to create the diagram by hand:
2 4 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 217/505
. Draw the reference variable GO_RENTAL (as an example) on the left side.
2. Write CREATE OBJECT go_rental ... above the reference variable.
3. Draw the object display of a car rental company on the right side and connect it to thereference variable.
4. Within this object, draw an area with a few implemented interface components.
5. Draw another reference variable GO_PARTNER at some distance below the first one.
6. Write GO_PARTNER = GO_RENTAL above the second reference variable and ask theparticipants to specify the content of the second reference variable.
7. Now, it depends what you want to show with the diagram. From a technical point of view,only an address is copied, so you can draw an arrow from GO_PARTNER to the object.
You must ask which components are addressed with GO_PARTNER.
In contrast, in the following graphic, you want to indicate the syntactic restriction of thesecond reference variable. Using the second variable, you can therefore only access theimplementing interface components because the static type is critical for the syntax check.
You could mention at this point to use the following command:
CREATE OBJECT rgo_partner TYPE lcl_rental EXPORTING iv_name= ’Travel Agency’.
You can generate an object of a class that implements the interface using an interfacereference.
If the class has implemented the interface, it is certain that all the components that can beaccessed syntactically after the cast assignment are available in the instance. A user canaddress the instance of the implementing class using the interface. The prefixing of theinterface name and the interface resolution operator is omitted. However, the user isrestricted to using the components from the interface.
In the example, the DISPLAY_PARTNER and CHECK_AVAILABILITY methods of theLIF_PARTNER interface can be accessed only after assigning the reference variableGO_PARTNER. It is not possible to access the specific components of the instance from theLCL_RENTAL (GET_NAME in the above example) class using the GO_PARTNER referencevariable.
The view is therefore, narrowed or at least remains unchanged. That is why you describe thistype of assignment of reference variables as up-cast. There is a switch from a view of severalcomponents to a view of a few components. The target reference can, of course, accept moredynamic types after the assignment, than it could before. Therefore, the term widening cast isalso suitable.
Lesson: Implement Polymorphism Using Interfaces
© Copyright . All rights reserved. 2 5
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 218/505
Generic Access with Interfaces
Figure 88: Row Type of the Internal Table in the Application Example
A typical area of use for up-cast assignments is preparation for generic access. A user who isnot interested in the finer points of the instances of the class that implement the interface butwho simply wants to address the components defined in the interface, could use an interfacereference for this access.
In the example shown, a travel agency (LCL_TRAVEL_AGENCY) needs to manage the variouskinds of business partners in one list. You must therefore type the row type of the internaltable as the reference to the interface LIF_PARTNER.
The travel agency only wants to request the services in order to display their attributes andcheck availability of the services. The relevant DISPLAY_PARTNER andCHECK_AVAILABILITY methods are defined in the LIF_PARTNER interface and implementedin all business partner classes.
The objects of different classes (LCL_HOTEL, LCL_RENTAL, and LCL_CARRIER in theexample) can be kept in an internal table, typed with interface references (LIF_PARTNER inthe example). The components defined in the interface can then be accessed uniformly.
For this example, the ADD_PARTNER method is therefore needed. This copies the referencesto all the kinds of business partners in the internal table. The import parameter of this methodis already typed as the reference to the interface.
Unit 4: Interfaces and Casting
2 6 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 219/505
Polymorphism – Generic Access Using the Interface Reference
Figure 89: Polymorphism – Generic Access Using the Interface Reference
Polymorphism can also be performed for interfaces. You can use interface references to callmethods, whereby you can execute different implementations depending on the object of thereference.
The dynamic type of the reference variable, not the static type, is used to search for theimplementation of a method. In the above example, go_partner->display_partner( )uses the class of the instance to which go_partner actually refers in order to search for theimplementation of display_partner . For example, it does not use the static type forgo_partner (which is always REF TO lif_partner ).
The implementation that is now executed when DISPLAY_PARTNER is called, thereforedepends on the object to which the interface reference GO_PARTNER currently refers. Whenobjects from different classes react differently to the same method calls, this is known aspolymorphism.
The option of performing polymorphism is one of the main strengths of interfaces. A clientcan handle different classes uniformly, irrespective of their implementation. The runtimesystem searches for the right implementation of a method on behalf of the client.
Polymorphism can be used to write programs that are highly generic, that is, they do not needto be changed significantly if use cases are added.
In the example, it will therefore be very easy to realize a boat rental addition. For example, therelevant class with the name LCL_SHIPPING will simply have to implement the LIF_PARTNERinterface and the method DISPLAY_PARTNER defined there. Business partner managementcan then easily include ship-owning companies and also request them to display theirattributes.
Demonstration: How to Implement Polymorphism Using Interfaces
Lesson: Implement Polymorphism Using Interfaces
© Copyright . All rights reserved. 2 7
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 220/505
To demonstrate how to implement polymorphism using interfaces, implement suitable partsof the SAPBC401_INT_D2 program.
Unit 4: Interfaces and Casting
2 8 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 221/505
Unit 4Exercise 12
193Implement Polymorphism Using Interfaces
Business Example
You now need to add a class that uses the previously defined interface. Travel agencies needto manage various business partners using the interface and access the general services ofthe business partners.
Template:
SAPBC401_INH_T2
Solution:
SAPBC401_INT_S2
Encourage the participants to perform the last step. Make it clear that this is about the use ofthe interface. Explain this several times using the Unified Modeling Language (UML). Theserver classes implement the interface. The client that now follows uses the interface byaccessing the server classes’ services using interface references.
The participants should consider carefully what they are doing, where, and why.
Task 1
Define a local class for travel agencies.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe template program with all its includes.
2. In the include program that contains the definition of the LIF_PARTNER interface, defineand implement the LCL_TRAVEL_AGENCY local class.
Hint:If you have not copied the template program, you can reduce your typing loadby copying the definition and implementation of the LCL_TRAVEL_AGENCY
class from the SAPBC401_INT_T2 template and includeBC401_INT_T2_AGENCY. You can also create the LCL_TRAVEL_AGENCYclass from scratch, without using templates.
3. As a private class attribute, add an internal table MT_PARTNER for the buffering ofreferences to the business partners who have implemented the LIF_PARTNER interface.
4. Define and implement a public method ADD_PARTNER so that the business partnerreferences can be added to the MT_PARTNERS list. Define a suitably typed importparameter IO_PARTNER.
© Copyright . All rights reserved. 2 9
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 222/505
5. Extend the implementation of the DISPLAY_ATTRIBUTES method in a way that it not onlydisplays information about the travel agency but also about its business partners. Use thepreviously defined DISPLAY_PARTNERS method.
Task 2
In the main program, generate a travel agency instance, transfer the references to the airlineto this instance, and add the attributes.
1. In the main program, define a suitably typed reference variable for your new travel agencyclass.
2. Using the reference, generate an instance of your class LCL_TRAVEL_AGENCY. Decidehow to fill out the attributes.
3. Call the ADD_PARTNER method to transfer the references to the generated airlineinstances to the travel agency.
4. Display the attributes of the travel agency (including information about its businesspartners) by calling its method DISPLAY_ATTRIBUTES.
SAPBC401_INH_S1
REPORT sapbc401_inh_s1. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetypeEXCEPTIONS wrong_planetype, display_attributes. CLASS-METHODS:class_constructor, display_n_o_airplanes, get_n_o_airplanes RETURNINGvalue(rv_count) TYPE i.
PROTECTED SECTION.
CONSTANTS: c_pos_1 TYPE i VALUE 30. PRIVATE SECTION. TYPES: ty_planetypes TYPESTANDARD TABLE OF saplane WITH NON-UNIQUE KEY planetype. DATA: mv_nameTYPE string, mv_planetype TYPE saplane-planetype, mv_weight TYPEsaplane-weight, mv_tankcap TYPE saplane-tankcap. CLASS-DATA:gv_n_o_airplanes TYPE i, gt_planetypes TYPE ty_planetypes. CLASS-METHODS: get_technical_attributes IMPORTING iv_type TYPE saplane-planetype EXPORTING ev_weight TYPE saplane-weight ev_tankcap TYPEsaplane-tankcap EXCEPTIONS wrong_planetype. ENDCLASS. "lcl_airplaneDEFINITION
*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. METHOD class_constructor. SELECT *FROM saplane INTO TABLE gt_planetypes. ENDMETHOD. "class_constructorMETHOD constructor. mv_name = iv_name. mv_planetype = iv_planetype.get_technical_attributes( EXPORTING iv_type = iv_planetype IMPORTINGev_weight = mv_weight ev_tankcap = mv_tankcap EXCEPTIONSwrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ELSE.gv_n_o_airplanes = gv_n_o_airplanes + 1. ENDIF. ENDMETHOD."constructor METHOD display_attributes. WRITE: / icon_ws_plane ASICON, / 'Name of Airplane'(001) , AT c_pos_1 mv_name, / 'Type ofAirplane:'(002), AT c_pos_1 mv_planetype, / 'Weight:'(003), AT c_pos_1mv_weight LEFT-JUSTIFIED, / 'Tank capacity:'(004), AT c_pos_1
mv_tankcap LEFT-JUSTIFIED. ENDMETHOD. "display_attributes METHODdisplay_n_o_airplanes. SKIP. WRITE: / 'Number of airplanes:'(ca1), ATc_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD.
Unit 4: Interfaces and Casting
21 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 223/505
"display_n_o_airplanes METHOD get_n_o_airplanes. rv_count =gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes METHODget_technical_attributes. DATA: ls_planetype TYPE saplane. READ TABLEgt_planetypes INTO ls_planetype WITH TABLE KEY planetype = iv_typeTRANSPORTING weight tankcap. IF sy-subrc = 0. ev_weight = ls_planetype-weight. ev_tankcap = ls_planetype-tankcap. ELSE. RAISEwrong_planetype. ENDIF. ENDMETHOD. "get_technical_attributes ENDCLASS.
"lcl_airplane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -***- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION. METHODS: constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_cargo TYPE s_plan_car EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: mv_cargo TYPE s_plan_car.
ENDCLASS. "lcl_cargo_plane DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor.
super->constructor( EXPORTING iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF. mv_cargo = iv_cargo. ENDMETHOD. "constructor
METHOD display_attributes.
super->display_attributes( ). WRITE:
Lesson: Implement Polymorphism Using Interfaces
© Copyright . All rights reserved. 211
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 224/505
/ 'Max Cargo:'(005), AT c_pos_1 mv_cargo LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributes
ENDCLASS. "lcl_cargo_plane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -** CLASS lcl_passenger_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
METHODS: constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_seats TYPE s_seatsmax
EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: mv_seats TYPE s_seatsmax.ENDCLASS. "lcl_passenger_plane DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_passenger_plane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor. super->constructor( EXPORTING iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF.
mv_seats = iv_seats. ENDMETHOD. "constructor
METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Seats:'(006), AT c_pos_1 mv_seats LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributesENDCLASS. "lcl_passenger_plane IMPLEMENTATION DATA: go_airplane TYPE REF TO lcl_airplane,
go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPE REF TO lcl_passenger_plane, gt_airplanes TYPE TABLE OF
Unit 4: Interfaces and Casting
212 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 225/505
REF TO lcl_airplane, gv_count TYPE i. START-OF-SELECTION.******************* lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype = 1.
IF sy-subrc = 0.* do nothing just now ENDIF.
CREATE OBJECT go_cargo EXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo = 533
EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.* do nothing just now ENDIF.
go_passenger->display_attributes( ). go_cargo->display_attributes( ). gv_count = lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: /'Number of airplanes'(ca1), gv_count.
Lesson: Implement Polymorphism Using Interfaces
© Copyright . All rights reserved. 213
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 226/505
Unit 4Solution 12
198Implement Polymorphism Using Interfaces
Business Example
You now need to add a class that uses the previously defined interface. Travel agencies needto manage various business partners using the interface and access the general services ofthe business partners.
Template:
SAPBC401_INH_T2
Solution:
SAPBC401_INT_S2
Encourage the participants to perform the last step. Make it clear that this is about the use ofthe interface. Explain this several times using the Unified Modeling Language (UML). Theserver classes implement the interface. The client that now follows uses the interface byaccessing the server classes’ services using interface references.
The participants should consider carefully what they are doing, where, and why.
Task 1
Define a local class for travel agencies.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe template program with all its includes.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
2. In the include program that contains the definition of the LIF_PARTNER interface, defineand implement the LCL_TRAVEL_AGENCY local class.
Hint:If you have not copied the template program, you can reduce your typing load
by copying the definition and implementation of the LCL_TRAVEL_AGENCYclass from the SAPBC401_INT_T2 template and includeBC401_INT_T2_AGENCY. You can also create the LCL_TRAVEL_AGENCYclass from scratch, without using templates.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
3. As a private class attribute, add an internal table MT_PARTNER for the buffering ofreferences to the business partners who have implemented the LIF_PARTNER interface.
a) See the source text excerpt from the model solution.
214 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 227/505
4. Define and implement a public method ADD_PARTNER so that the business partnerreferences can be added to the MT_PARTNERS list. Define a suitably typed importparameter IO_PARTNER.
a) See the source text excerpt from the model solution.
5. Extend the implementation of the DISPLAY_ATTRIBUTES method in a way that it not only
displays information about the travel agency but also about its business partners. Use thepreviously defined DISPLAY_PARTNERS method.
a) See the source text excerpt from the model solution.
Task 2
In the main program, generate a travel agency instance, transfer the references to the airlineto this instance, and add the attributes.
1. In the main program, define a suitably typed reference variable for your new travel agencyclass.
a) See the source text excerpt from the model solution.
2. Using the reference, generate an instance of your class LCL_TRAVEL_AGENCY. Decidehow to fill out the attributes.
a) See the source text excerpt from the model solution.
3. Call the ADD_PARTNER method to transfer the references to the generated airlineinstances to the travel agency.
a) See the source text excerpt from the model solution.
4. Display the attributes of the travel agency (including information about its businesspartners) by calling its method DISPLAY_ATTRIBUTES.
a) See the source text excerpt from the model solution.
SAPBC401_INH_S1
REPORT sapbc401_inh_s1. TYPE-POOLS icon.*------------------------------------------------------------------* *CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetypeEXCEPTIONS wrong_planetype, display_attributes. CLASS-METHODS:class_constructor, display_n_o_airplanes, get_n_o_airplanes RETURNINGvalue(rv_count) TYPE i.
PROTECTED SECTION.
CONSTANTS: c_pos_1 TYPE i VALUE 30. PRIVATE SECTION. TYPES: ty_planetypes TYPESTANDARD TABLE OF saplane WITH NON-UNIQUE KEY planetype. DATA: mv_nameTYPE string, mv_planetype TYPE saplane-planetype, mv_weight TYPEsaplane-weight, mv_tankcap TYPE saplane-tankcap. CLASS-DATA:gv_n_o_airplanes TYPE i, gt_planetypes TYPE ty_planetypes. CLASS-METHODS: get_technical_attributes IMPORTING iv_type TYPE saplane-planetype EXPORTING ev_weight TYPE saplane-weight ev_tankcap TYPEsaplane-tankcap EXCEPTIONS wrong_planetype. ENDCLASS. "lcl_airplaneDEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*
Lesson: Implement Polymorphism Using Interfaces
© Copyright . All rights reserved. 215
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 228/505
CLASS lcl_airplane IMPLEMENTATION. METHOD class_constructor. SELECT *FROM saplane INTO TABLE gt_planetypes. ENDMETHOD. "class_constructorMETHOD constructor. mv_name = iv_name. mv_planetype = iv_planetype.get_technical_attributes( EXPORTING iv_type = iv_planetype IMPORTINGev_weight = mv_weight ev_tankcap = mv_tankcap EXCEPTIONSwrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ELSE.gv_n_o_airplanes = gv_n_o_airplanes + 1. ENDIF. ENDMETHOD.
"constructor METHOD display_attributes. WRITE: / icon_ws_plane ASICON, / 'Name of Airplane'(001) , AT c_pos_1 mv_name, / 'Type ofAirplane:'(002), AT c_pos_1 mv_planetype, / 'Weight:'(003), AT c_pos_1mv_weight LEFT-JUSTIFIED, / 'Tank capacity:'(004), AT c_pos_1mv_tankcap LEFT-JUSTIFIED. ENDMETHOD. "display_attributes METHODdisplay_n_o_airplanes. SKIP. WRITE: / 'Number of airplanes:'(ca1), ATc_pos_1 gv_n_o_airplanes LEFT-JUSTIFIED. ENDMETHOD."display_n_o_airplanes METHOD get_n_o_airplanes. rv_count =gv_n_o_airplanes. ENDMETHOD. "get_n_o_airplanes METHODget_technical_attributes. DATA: ls_planetype TYPE saplane. READ TABLEgt_planetypes INTO ls_planetype WITH TABLE KEY planetype = iv_typeTRANSPORTING weight tankcap. IF sy-subrc = 0. ev_weight = ls_planetype-weight. ev_tankcap = ls_planetype-tankcap. ELSE. RAISEwrong_planetype. ENDIF. ENDMETHOD. "get_technical_attributes ENDCLASS.
"lcl_airplane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -***- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION. METHODS: constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_cargo TYPE s_plan_car EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: mv_cargo TYPE s_plan_car.
ENDCLASS. "lcl_cargo_plane DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_cargo_plane IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor.
super->constructor( EXPORTING
Unit 4: Interfaces and Casting
216 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 229/505
iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF.
mv_cargo = iv_cargo. ENDMETHOD. "constructor
METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Cargo:'(005), AT c_pos_1 mv_cargo LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributes
ENDCLASS. "lcl_cargo_plane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -** CLASS lcl_passenger_plane DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
METHODS: constructor IMPORTING iv_name TYPE string iv_planetype TYPE saplane-planetype iv_seats TYPE s_seatsmax
EXCEPTIONS wrong_planetype,
display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: mv_seats TYPE s_seatsmax.ENDCLASS. "lcl_passenger_plane DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_passenger_plane IMPLEMENTATION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor. super->constructor( EXPORTING iv_name = iv_name iv_planetype = iv_planetype EXCEPTIONS wrong_planetype = 1 ). IF sy-subrc <> 0. RAISE wrong_planetype. ENDIF.
mv_seats = iv_seats. ENDMETHOD. "constructor
Lesson: Implement Polymorphism Using Interfaces
© Copyright . All rights reserved. 217
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 230/505
METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Seats:'(006), AT c_pos_1 mv_seats LEFT-JUSTIFIED. ULINE. ENDMETHOD. "display_attributes
ENDCLASS. "lcl_passenger_plane IMPLEMENTATION DATA: go_airplane TYPE REF TO lcl_airplane,
go_cargo TYPE REF TO lcl_cargo_plane, go_passenger TYPE REF TO lcl_passenger_plane, gt_airplanes TYPE TABLE OFREF TO lcl_airplane, gv_count TYPE i. START-OF-SELECTION.******************* lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT go_passenger EXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400' iv_seats = 345 EXCEPTIONS wrong_planetype = 1.
IF sy-subrc = 0.* do nothing just now ENDIF.
CREATE OBJECT go_cargo EXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F' iv_cargo = 533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc = 0.* do nothing just now ENDIF.
go_passenger->display_attributes( ). go_cargo->display_attributes( ). gv_count = lcl_airplane=>get_n_o_airplanes( ). SKIP 2. WRITE: /'Number of airplanes'(ca1), gv_count.
Unit 4: Interfaces and Casting
218 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 231/505
LESSON SUMMARYYou should now be able to:
● Implement polymorphism using interfaces
Lesson: Implement Polymorphism Using Interfaces
© Copyright . All rights reserved. 219
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 232/505
Unit 4Lesson 3
204Joining Classmodels Using Interfaces
LESSON OVERVIEWThis lesson explains the method of joining classmodels using interfaces.
You have created this lesson for the sake of completeness. In other words, it serves to buildon the analogy with regular inheritance rather than presenting significant new programmingtechniques.
Business ExampleAs a developer, create different interfaces to join classmodels of the airplane classes. For thisreason, you require the following knowledge:
● An understanding of submodels
● An understanding of joining submodels
● An understanding of interface hierarchies
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement down-casts with interfaces
● Join different submodels using interfaces
● Create and use interface hierarchies
22 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 233/505
Down-Casts with Interfaces
Figure 90: Down-Cast Assignment and Exception Handling in the Application Example
If you want to assign an interface reference to a class reference where the class hasimplemented the interface, you must use the down-cast assignment operator MOVE ... ?TO ...or its short form ?=. Otherwise, the system would return a message stating that it is notcertain that all components that can be accessed syntactically after the cast assignment areactually available in the instance. As a rule, the implementing class contains morecomponents than the interface.
Interface reference variables can contain references to instances of the implementing class atruntime. After assigning this type of reference back to a reference to the implementing class,clients are no longer limited to interface components. For example, all components of theLCL_CARRIER instance can be accessed again after the assignment using referenceR_CARRIER.
How to Join Different Submodels Using Interfaces
To demonstrate how to join different submodels using interfaces, implement suitable partsof program SAPBC410_INT_D3.
Lesson: Joining Classmodels Using Interfaces
© Copyright . All rights reserved. 221
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 234/505
Unit 4: Interfaces and Casting
222 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 235/505
Unit 4Exercise 13
207Join Classmodels Using Interfaces
Business Example
You now do the final step and add the car rental company with its vehicles to your own objectmodel. By implementing the already defined interface, you can easily ensure that the carrental company can be added to the list of business partners of the travel agency.
Template:
SAPBC401_INT_T3
Solution:
SAPBC401_INT_S3
Task 1
Copy the definitions and implementations of classes LCL_RENTAL and the vehicle classes(LCL_VEHICLE, LCL_TRUCK, and LCL_BUS) to your program and create instances of theseclasses.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe template program with all its includes.
2. If you have copied the template program, analyze it and continue with the next task. If youwant to continue working with your own program then first copy include programBC401_INT_T3_RENTAL (recommended name: ZBC401_##_RENTAL, where ## is yourtwo-digit group number) and make the new include program part of your own program.
3. In your main program, create an instance of LCL_RENTAL and a number of instances ofvehicle classes. Add all the vehicles to the rental company’s list of vehicles by callingmethod ADD_VEHICLE of LCL_RENTAL.
Hint:To reduce the typing effort you can copy and paste the relevant coding fromthe main program of SAPBC401_INT_T3.
Task 2
Implement interface LIF_PARTNER in class LCL_RENTAL.
1. Call method ADD_PARTNER to add the instance of LCL_RENTAL to the travel agency’s listof business partners.
2. Perform a syntax check. Why does this method call cause a syntax error?
© Copyright . All rights reserved. 223
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 236/505
3. Go to the definition part of class LCL_RENTAL and declare the implementation of interfaceLIF_PARTNER.
4. Provide an implementation of the method defined in the interface.
5. Activate the include with the definition and implementation of LCL_RENTAL. Then go tothe main program and perform another syntax check. Why does the call ofADD_PARTNER now work for the car rental company?
Include BC401_INT_S3_RENTAL
*---------------------------------------------------------------------* * CLASS lcl_vehicle DEFINITION*---------------------------------------------------------------------* CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_make TYPE string, display_attributes. PRIVATE SECTION.DATA: mv_make TYPE string. ENDCLASS. "lcl_vehicle DEFINITION*---------------------------------------------------------------------* * CLASS lcl_vehicle IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION. METHOD constructor. mv_make =iv_make. ENDMETHOD. "constructor METHOD display_attributes. WRITEmv_make. ENDMETHOD. "display_attributes ENDCLASS. "lcl_vehicleIMPLEMENTATION*---------------------------------------------------------------------
* * CLASS lcl_truck DEFINITION*---------------------------------------------------------------------* CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. PUBLICSECTION. METHODS: constructor IMPORTING iv_make TYPE string iv_cargoTYPE s_plan_car, display_attributes REDEFINITION, PRIVATE SECTION.DATA: mv_cargo TYPE s_plan_car. ENDCLASS. "lcl_truck DEFINITION*---------------------------------------------------------------------* * CLASS lcl_truck IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_truck IMPLEMENTATION. METHOD constructor. super->constructor( iv_make ). mv_cargo = iv_cargo. ENDMETHOD. "constructorMETHOD display_attributes. WRITE / icon_ws_truck AS ICON. super->display_attributes( ). WRITE: 20 'Max. Cargo:'(005), mv_cargo. ULINE.ENDMETHOD. "display_attributes ENDCLASS. "lcl_truck DEFINITION
*---------------------------------------------------------------------* * CLASS lcl_bus DEFINITION*---------------------------------------------------------------------* CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle. PUBLICSECTION. METHODS: constructor IMPORTING iv_make TYPE stringiv_passengers TYPE i, display_attributes REDEFINITION. PRIVATESECTION. DATA: mv_passengers TYPE i. ENDCLASS. "lcl_bus DEFINITION*---------------------------------------------------------------------* * CLASS lcl_bus IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_bus IMPLEMENTATION. METHOD constructor. super->constructor( iv_make ). mv_passengers = iv_passengers. ENDMETHOD."constructor METHOD display_attributes. WRITE: /icon_transportation_mode AS ICON. super->display_attributes( ). WRITE:
20 'Max. Passengers: '(006), mv_passengers. ULINE. ENDMETHOD."display_attributes ENDCLASS. "lcl_bus DEFINITION
Unit 4: Interfaces and Casting
224 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 237/505
*---------------------------------------------------------------------* * CLASS lcl_rental DEFINITION*---------------------------------------------------------------------* CLASS lcl_rental DEFINITION. PUBLIC SECTION.
INTERFACES: lif_partner. METHODS: constructor IMPORTING iv_name TYPE string, add_vehicleIMPORTING io_vehicle TYPE REF TO lcl_vehicle, display_attributes.PRIVATE SECTION. DATA: mv_name TYPE string, mt_vehicles TYPE TABLE OFREF TO lcl_vehicle. ENDCLASS. "lcl_rental DEFINITION*---------------------------------------------------------------------* * CLASS lcl_rental IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD constructor. mv_name =iv_name. ENDMETHOD. "constructor METHOD add_vehicle. APPEND io_vehicleTO mt_vehicles. ENDMETHOD. "add_vehicle METHOD display_attributes.DATA: lo_vehicle TYPE REF TO lcl_vehicle. WRITE: /icon_transport_proposal AS ICON, mv_name. ULINE. ULINE. LOOP AT
mt_vehicles INTO lo_vehicle. lo_vehicle->display_attributes( ).ENDLOOP. ENDMETHOD. "display_attributes
METHOD lif_partner~display_partner. me->display_attributes( ). ENDMETHOD. "lif_partner~display_partner ENDCLASS. "lcl_rental IMPLEMENTATION
Lesson: Joining Classmodels Using Interfaces
© Copyright . All rights reserved. 225
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 238/505
Unit 4Solution 13
210Join Classmodels Using Interfaces
Business Example
You now do the final step and add the car rental company with its vehicles to your own objectmodel. By implementing the already defined interface, you can easily ensure that the carrental company can be added to the list of business partners of the travel agency.
Template:
SAPBC401_INT_T3
Solution:
SAPBC401_INT_S3
Task 1
Copy the definitions and implementations of classes LCL_RENTAL and the vehicle classes(LCL_VEHICLE, LCL_TRUCK, and LCL_BUS) to your program and create instances of theseclasses.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe template program with all its includes.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
2. If you have copied the template program, analyze it and continue with the next task. If youwant to continue working with your own program then first copy include programBC401_INT_T3_RENTAL (recommended name: ZBC401_##_RENTAL, where ## is yourtwo-digit group number) and make the new include program part of your own program.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
3. In your main program, create an instance of LCL_RENTAL and a number of instances ofvehicle classes. Add all the vehicles to the rental company’s list of vehicles by callingmethod ADD_VEHICLE of LCL_RENTAL.
Hint:To reduce the typing effort you can copy and paste the relevant coding fromthe main program of SAPBC401_INT_T3.
a) See the source text excerpt from the model solution.
Task 2
Implement interface LIF_PARTNER in class LCL_RENTAL.
1. Call method ADD_PARTNER to add the instance of LCL_RENTAL to the travel agency’s list
of business partners.
226 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 239/505
a) See the source text excerpt from the model solution.
2. Perform a syntax check. Why does this method call cause a syntax error?
The up-cast in the parameter passing of the method does not work because the typesLCL_RENTAL and LIF_PARTNER are not compatible. They will become compatible,though, as soon as LCL_RENTAL implements the interface.
3. Go to the definition part of class LCL_RENTAL and declare the implementation of interfaceLIF_PARTNER.
a) See the source text excerpt from the model solution.
4. Provide an implementation of the method defined in the interface.
a) See the source text excerpt from the model solution.
5. Activate the include with the definition and implementation of LCL_RENTAL. Then go tothe main program and perform another syntax check. Why does the call ofADD_PARTNER now work for the car rental company?
Because now the types LCL_RENTAL and LIF_PARTNER are compatible. LCL_RENTALimplements interface LIF_PARTNER. Any instance of LCL_RENTAL is accepted as abusiness partner.
Include BC401_INT_S3_RENTAL
*---------------------------------------------------------------------* * CLASS lcl_vehicle DEFINITION*---------------------------------------------------------------------* CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS: constructorIMPORTING iv_make TYPE string, display_attributes. PRIVATE SECTION.
DATA: mv_make TYPE string. ENDCLASS. "lcl_vehicle DEFINITION*---------------------------------------------------------------------* * CLASS lcl_vehicle IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION. METHOD constructor. mv_make =iv_make. ENDMETHOD. "constructor METHOD display_attributes. WRITEmv_make. ENDMETHOD. "display_attributes ENDCLASS. "lcl_vehicleIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_truck DEFINITION*---------------------------------------------------------------------* CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. PUBLICSECTION. METHODS: constructor IMPORTING iv_make TYPE string iv_cargoTYPE s_plan_car, display_attributes REDEFINITION, PRIVATE SECTION.
DATA: mv_cargo TYPE s_plan_car. ENDCLASS. "lcl_truck DEFINITION*---------------------------------------------------------------------* * CLASS lcl_truck IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_truck IMPLEMENTATION. METHOD constructor. super->constructor( iv_make ). mv_cargo = iv_cargo. ENDMETHOD. "constructorMETHOD display_attributes. WRITE / icon_ws_truck AS ICON. super->display_attributes( ). WRITE: 20 'Max. Cargo:'(005), mv_cargo. ULINE.ENDMETHOD. "display_attributes ENDCLASS. "lcl_truck DEFINITION*---------------------------------------------------------------------* * CLASS lcl_bus DEFINITION*---------------------------------------------------------------------* CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle. PUBLICSECTION. METHODS: constructor IMPORTING iv_make TYPE string
iv_passengers TYPE i, display_attributes REDEFINITION. PRIVATESECTION. DATA: mv_passengers TYPE i. ENDCLASS. "lcl_bus DEFINITION
Lesson: Joining Classmodels Using Interfaces
© Copyright . All rights reserved. 227
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 240/505
*---------------------------------------------------------------------* * CLASS lcl_bus IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_bus IMPLEMENTATION. METHOD constructor. super->constructor( iv_make ). mv_passengers = iv_passengers. ENDMETHOD."constructor METHOD display_attributes. WRITE: /icon_transportation_mode AS ICON. super->display_attributes( ). WRITE:
20 'Max. Passengers: '(006), mv_passengers. ULINE. ENDMETHOD."display_attributes ENDCLASS. "lcl_bus DEFINITION*---------------------------------------------------------------------* * CLASS lcl_rental DEFINITION*---------------------------------------------------------------------* CLASS lcl_rental DEFINITION. PUBLIC SECTION.
INTERFACES: lif_partner. METHODS: constructor IMPORTING iv_name TYPE string, add_vehicleIMPORTING io_vehicle TYPE REF TO lcl_vehicle, display_attributes.PRIVATE SECTION. DATA: mv_name TYPE string, mt_vehicles TYPE TABLE OF
REF TO lcl_vehicle. ENDCLASS. "lcl_rental DEFINITION*---------------------------------------------------------------------* * CLASS lcl_rental IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD constructor. mv_name =iv_name. ENDMETHOD. "constructor METHOD add_vehicle. APPEND io_vehicleTO mt_vehicles. ENDMETHOD. "add_vehicle METHOD display_attributes.DATA: lo_vehicle TYPE REF TO lcl_vehicle. WRITE: /icon_transport_proposal AS ICON, mv_name. ULINE. ULINE. LOOP ATmt_vehicles INTO lo_vehicle. lo_vehicle->display_attributes( ).ENDLOOP. ENDMETHOD. "display_attributes
METHOD lif_partner~display_partner. me->display_attributes( ). ENDMETHOD. "lif_partner~display_partner ENDCLASS. "lcl_rental IMPLEMENTATION
Unit 4: Interfaces and Casting
228 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 241/505
Implementation of Interface Hierarchies
Compound interfaces are discussed only here as a preview of what is covered later in thecourse. Do not spend too much time on this topic at this stage.
Figure 91: Interface Hierarchy in the Application Example
You have already seen several times that an interface implementation strongly resemblesregular inheritance. You therefore need to ask what the interface counterpart of hierarchicalinheritance looks like. You want to explain interface hierarchies using an application example.
In this example, you need to know whether it would be useful to define a further service “roomreservation” in the interface LIF_PARTNER. In this case, the classes LCL_CARRIER andLCL_RENTAL would have to implement the appropriate method because they have integratedthe interface LIF_PARTNER. However, to implement a room reservation keeping the samesemantics is not conceivable for airlines or car rental companies.
However, because there are several other business partner types for which animplementation would be useful for example, motels and hotels, the method needs to becentrally defined and not individually for motels and hotels. On the other hand, the option ofeasily extending the model with other accommodation provider types, for example,guesthouse must be retained.
Lesson: Joining Classmodels Using Interfaces
© Copyright . All rights reserved. 229
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 242/505
Compound Interface in Unified Modeling Language (UML) Notation
Figure 92: Compound Interface in UML Notation
In ABAP Objects, interfaces like regular superclasses can include other interfaces. As withregular inheritance, the result is interface hierarchies of any depth.
You can regard the including interface as a specialization of the included interface. Itrepresents an extension of the included interface. The including interface is known as acompound interface. An included interface represents a component of another interface andis therefore known as a component interface. An elementary interface does not contain otherinterfaces in itself.
The UML notation corresponds to the implementation of an elementary interface by a class.
Definition and Implementation of Compound Interfaces – Syntax
Figure 93: Definition and Implementation of Compound Interfaces – Syntax
Unit 4: Interfaces and Casting
23 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 243/505
As with regular inheritance, the implementing class only needs to list the compound interfacein order to integrate all components. Nevertheless, the components of the componentinterfaces keep their original names:
component_interface_name~component_name
They are therefore not prefixed by the name of the compound interface.
All implementations of methods from all higher level interfaces must take place in the firstimplementing class. Alias names are suitable for short-form syntax when accessingcomponents from different interfaces. At the same time, get a central documentary view of allcomponents with the definition of these alias names in the implementing class.
Addressing Components in Compound Interfaces – Syntax
Figure 94: Addressing Components in Compound Interfaces – Syntax
The same possibilities apply for accessing its components from a compound interface and forcast assignments.
Correct Use of Interfaces
Figure 95: Using Interfaces
Lesson: Joining Classmodels Using Interfaces
© Copyright . All rights reserved. 231
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 244/505
Interfaces are used to describe protocols for using components without connecting a kind ofimplementation. An intermediate layer is introduced between the client and the server toprotect the client from the explicit server, thereby making the client independent.
Interfaces enable different classes to be handled uniformly, provided they implemented theinterfaces. As with inheritance, you can also perform polymorphism using interface reference
variables.As with regular inheritance, the definition of an interface means an abstraction of theimplementing classes to a specific partial aspect.
Multiple inheritances can be simulated using interfaces. If several interfaces are included, allcomponents are available to all of the interfaces and you must implement all methods.
Unit 4: Interfaces and Casting
232 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 245/505
LESSON SUMMARYYou should now be able to:
● Implement down-casts with interfaces
● Join different submodels using interfaces
● Create and use interface hierarchies
Lesson: Joining Classmodels Using Interfaces
© Copyright . All rights reserved. 233
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 246/505
Unit 4: Interfaces and Casting
234 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 247/505
Unit 4
219Learning Assessment
1. Which of the following technically differentiates interfaces from regular inheritance?
Choose the correct answer.
X A Interfaces are superclasses that can be instantiated
X B Interfaces do not have an implementation part
X C Interfaces have only public components
2. Which of the following is defined in the interface?
Choose the correct answer.
X A Services
X B Methods
X C Classes
3. Which of the following statements is used to implement an interface in a class?Choose the correct answer.
X A ALIASES
X B METHOD
X C INTERFACES
4. You can access interface components only by using an object reference.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 235
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 248/505
5. Which of the following is used to search for the implementation of a method?
Choose the correct answers.
X A The dynamic type reference variable
X B The static type reference variable
X C Method parameters
X D A class
6. Which of the following is the main strength of interfaces?
Choose the correct answer.
X A Events
X B Inheritance
X C Polymorphism
7. ?= is the down-cast assignment operator.
Determine whether this statement is true or false.
X True
X False
8. Interface reference variables can contain references to instances of the class that is notimplemented at runtime.
Determine whether this statement is true or false.
X True
X False
9. Which of the following implementation strongly resembles regular inheritance?
Choose the correct answer.
X A Interface
X B Class
X C Method
Unit 4: Learning Assessment
236 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 249/505
10. Interfaces like regular superclasses can include other interfaces.
Determine whether this statement is true or false.
X True
X False
Unit 4: Learning Assessment
© Copyright . All rights reserved. 237
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 250/505
Unit 4
222Learning Assessment- Answers
1. Which of the following technically differentiates interfaces from regular inheritance?
Choose the correct answer.
X A Interfaces are superclasses that can be instantiated
X B Interfaces do not have an implementation part
X C Interfaces have only public components
2. Which of the following is defined in the interface?
Choose the correct answer.
X A Services
X B Methods
X C Classes
3. Which of the following statements is used to implement an interface in a class?
Choose the correct answer.
X A ALIASES
X B METHOD
X C INTERFACES
4. You can access interface components only by using an object reference.Determine whether this statement is true or false.
X True
X False
238 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 251/505
5. Which of the following is used to search for the implementation of a method?
Choose the correct answers.
X A The dynamic type reference variable
X B The static type reference variable
X C Method parameters
X D A class
6. Which of the following is the main strength of interfaces?
Choose the correct answer.
X A Events
X B Inheritance
X C Polymorphism
7. ?= is the down-cast assignment operator.
Determine whether this statement is true or false.
X True
X False
8. Interface reference variables can contain references to instances of the class that is notimplemented at runtime.
Determine whether this statement is true or false.
X True
X False
9. Which of the following implementation strongly resembles regular inheritance?
Choose the correct answer.
X A Interface
X B Class
X C Method
Unit 4: Learning Assessment- Answers
© Copyright . All rights reserved. 239
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 252/505
10. Interfaces like regular superclasses can include other interfaces.
Determine whether this statement is true or false.
X True
X False
Unit 4: Learning Assessment- Answers
24 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 253/505
UNIT 5 Object-Oriented Events
Lesson 1
Implementing Events in Local Classes 242Exercise 14: Implement Events in Local Classes 251
Lesson 2
Implementing Events in Local Interfaces 256
Exercise 15: Implement Event Handling for Interfaces 257
UNIT OBJECTIVES
● Implement event-controlled method calls
● Trigger and handle events
● Register for events
● Explain visibility sections in event handling
● Implement events in local interfaces
© Copyright . All rights reserved. 241
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 254/505
Unit 5Lesson 1
226Implementing Events in Local Classes
LESSON OVERVIEWThis lesson explains the method of implementing events in local classes.
Note:This application example used here does not specify that the events aredefined in superclasses or interfaces.
Therefore, before you look at the first graphic about the event concept, you could also startthe course by turning the approach around and having the participants discuss which classshould do the defining and triggering and which should do the handling. Assuming that theparticipants have understood the inheritance concept, they should be able to come up withthe solution themselves. The same applies to the optional exercise in which participantsdefine the event in the interface.
Business Example
As a developer, you want to implement event-controlled behavior from your model in ABAPObjects. For this reason, you require the following knowledge:
● Define and trigger events
● Register events
● Implement events in local classes
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement event-controlled method calls
● Trigger and handle events● Register for events
● Explain visibility sections in event handling
242 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 255/505
Event-Controlled Method Calls
Figure 96: Event-Controlled Method Calls
Besides attributes and methods, classes and their instances can contain a third type ofcomponent events. Instance events can be triggered by the instances of the class, while staticinstance events can be triggered by the class itself.
Events can also be defined as interface components.
Given the right circumstances, handler methods can now react to the triggering of this event.This means that the runtime system may call these handler methods after the event has beentriggered. In other words, the client usually does not call the handler method directly.
This results in a completely different modeling concept. While you are developing the classthat triggers the event, you do not need to know anything about the class that is handling it.The triggering class sends a specific message to all classes and, if need be, their instances ofthe running program. At the time of development, it is completely unclear what type ofhandlers will be there and how many will be used.
Because of the definition of the handler method, the range of possible results can benarrowed down, but which, if any, of these results actually will occur can be determined onlyafter the event has been triggered.
An event can have exporting parameters, which means that, in contrast to the explicit methodcall, the calling program determines the protocol in this case.
In this application example, after an instance in the vehicle class is created, it triggers theevent vehicle created. Different instances receive this and process each one differently. Therental car company considers purchasing a vehicle, while the vehicle registration officeregisters the car, and so on.
Caution:Do not confuse this concept of events in object-oriented programming withevents in the ABAP runtime system such as LOAD-OF-PROGRAM, START-OF-SELECTION, and so on. Also, do not confuse it with background processing orworkflow control.
Lesson: Implementing Events in Local Classes
© Copyright . All rights reserved. 243
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 256/505
Event Handling in a UML Class Diagram
Figure 97: Event Handling in a UML Class Diagram
In UML class diagrams, a dotted arrow with the stereotype «handlesEventOf» points fromthe handling class to the triggering class. The event definition and signature only appearimplicitly in the handling class within the handler method. The handler methods are separatedfrom the other methods using the stereotype «eventHandler» .
Trigger and Handle Events
Figure 98: Defining and Triggering Events – Syntax
Keep in mind that, depending on the status of your application, you may not need to programall steps. The separation of cause and effect in your programming should be reflected in theway you construct complex applications. Often, the event is already triggered and all you haveto do is create another event handler.
Unit 5: Object-Oriented Events
244 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 257/505
Within a class, instance events are defined using the EVENTS statement, while static eventsare defined using the CLASS-EVENTS statement. Events can only have exporting parameters,which must be passed by value.
A class or instance can trigger an event at runtime using the RAISE EVENT statement. Bothinstance events and static events can be triggered in instance methods. You can trigger static
events only in static methods.When an event is triggered, the handler methods that are registered to this event are called insequence. Of course, these can trigger more events of their own.
Handling Events – Syntax
Figure 99: Handling Events – Syntax
Instance events or static methods can be defined within a class to handle events. To do so,you must specify the event using the FOR EVENT statement and the class or interface inwhich the event was defined using the OF statement.
If the event contains exporting parameters and you want to be able to address thesesyntactically, you must have specified the exporting parameters immediately afterIMPORTING in the definition of the method. The handler method’s signature can consist ofnothing more than the exporting parameters of the associated event. The parameters aretyped by the handler method during the definition of the event. The object that triggers theevent determines the protocol.
In addition to the explicitly defined exporting parameters, the predefined importing parameterSENDER can always be listed. By using that parameter, you can place a reference to theevent-trigger object into the handler method.
Therefore, handler methods are usually called by triggered events RAISE EVENT. However,they can also be called explicitly (CALL METHOD).
To Trigger and Handle Events
This procedure summarizes all of the required programming steps for event controlling:
Lesson: Implementing Events in Local Classes
© Copyright . All rights reserved. 245
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 258/505
1. Define an event in a class. The syntax for this is EVENTS eventname, CLASS-EVENTSeventname.
2. Trigger an event in a class or instance. The syntax for this is RAISE EVENT eventname.
3. Define and implement the handler method in the Handler Class. The syntax for this is[CLASS -] METHODS … FOR EVENT …. OF.
4. Register events at runtime. The syntax for this is SET HANDLER.
Demonstration: How to Trigger and Handle Events
To demonstrate how to trigger and handle events, implement suitable parts of programSAPBC410_EVE_BASIC_D1.
Event Registration
Figure 100: Registering Event Handling
You can use executable programs SAPBC401_EVE_BASIC_D1 ... SAPBC401_EVE_BASIC_D3to illustrate various aspects of event registration. Make sure you show the list of registeredhandlers for a given instance and event in the ABAP Debugger .
The most common mistake in relation to event control is forgetting the registration. Be sureto explain why the registration is so important. Debug executable programSAPBC401_EVE_BASIC_D1 to illustrate this.
The definition of the handler method only specifies how and to which event of which class, themethod will react. At runtime, it needs to be determined which possible reactions will actuallytake place and when each of these will happen.
When triggering instance events, you also have to specify what event the reaction will trigger.If instance methods are set to carry out the reaction, you also have to specify whichinstance(s) will perform the reaction.
Unit 5: Object-Oriented Events
246 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 259/505
These specifications are collectively known as registration. The registration is always carriedout using the trigger. When the event is triggered, the runtime uses the registrations of thetrigger to determine which event handler methods need to be called.
In this example, handler methods are defined for the event of the vehicle class, the car rentalclass, and the vehicle registration class. However, you can only predetermine which car rental
instances and vehicle registration instances will react to which vehicle instance, and whenthey will do so.
Registrations can also be revoked.
Registering Event Handling – Syntax
Figure 101: Registering Event Handling – Syntax
Events are registered using the SET HANDLER statement. Registration is only active atprogram runtime.
With instance events, FOR is followed by the reference to the object that triggers the event.
The addition ACTIVATION 'X' is optional during registration. To undo the registration, useACTIVATION.
You can register several methods with one SET-HANDLER statement:
SET HANDLER ref_handler_1->on_eventname_1 ...
ref_handler_n->on_eventname_n FOR ....
Demonstration: How to Register for Events of One Instance
To demonstrate how to register for events of one instance, implement suitable parts ofprogram SAPBC410_EVE_BASIC_D2.
Demonstration: How to Register for Events of All Instances of a Class
Lesson: Implementing Events in Local Classes
© Copyright . All rights reserved. 247
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 260/505
To demonstrate how to register for events of all instances of a class, implement suitableparts of program SAPBC410_EVE_BASIC_D3.
Event Handler Tables
Figure 102: Registration/Deregistration Handler Tables
Every object or class that has defined events has an internal table that is the handler table. Allhandler methods that are registered to the various events are listed within the table. Forinstance methods, the handler table also contains references to the registered objects.
Hint:Objects that are registered for event handling are not deleted by the garbagecollector, even if there are no remaining references to them.
Note:It is even possible to add or remove event handlers for a given event while an event
handler for exactly this event is executed. If a new event handler is registered, thenthis event handler is added to the end of the sequence and executed when its timecomes. If an existing event handler is deregistered, then this handler is deletedimmediately from the event handler method sequence.
Visibility Sections in Event Handling
Apply the event handling concept in your demonstration program. Define an instance eventVEHICLE_CREATED in LCL_VEHICLE and raise it in the instance constructor. Replace theADD_VEHICLE method of LCL_RENTAL by an event handler. Now, your demonstration
Unit 5: Object-Oriented Events
248 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 261/505
program should resemble the executable program SAPBC401_EVE_D1. Run your program indebugging mode.
We suggest that you then let the participants do the first exercise of this lesson.
To finish the discussion of event handling, you should demonstrate the definition of an eventPARTNER_CREATED in interface LIF_PARTNER and how it is handledin LCL_TRAVEL_AGENCY. Emphasize, that there is no syntax check that ensures that allimplementing classes actually raise the event. If there is enough time, let the participantsrepeat this in the optional second exercise of this lesson. Events are also subject to thevisibility concept and can therefore be public, protected, or private. Event handler methodsalso have visibility attributes.
● The visibility of an event determines where the event can be handled.
PUBLIC
ALL
PROTECTED
Can only be handled by users within that class or its subclasses
PRIVATE
Can only be handled within its class
● The visibility of a handler method controls where the registration of the method can beperformed that is, the locations where the SET HANDLER statement may be programmed.
PUBLIC
Anywhere in the program
PROTECTED
Can be handled by users within that class or its subclasses
PRIVATE
Can only be handled within its class
Event-handler methods can only have the same visibility or more restricted visibility than theevents they refer to.
Lesson: Implementing Events in Local Classes
© Copyright . All rights reserved. 249
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 262/505
Unit 5: Object-Oriented Events
25 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 263/505
Unit 5Exercise 14
235Implement Events in Local Classes
Business Example
Include airplane and vehicle references in the airline and the car rental company’s lists. Thisprocess is to be event-controlled.
Template:
SAPBC401_INT_S3
Solution:
SAPBC401_EVE_S1
Task 1
Define an event for the creation of an airplane. Trigger and handle it so that the reference tothe airplane is entered into the airline’s list of airplanes.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe template program.
Identify the class that is suitable for triggering the event and the class that you should usefor handling the event. Use your UML diagram if necessary.
2. Define the public event AIRPLANE_CREATED in class LCL_AIRPLANE. Choose a suitablemethod of LCL_AIRPLANE and fire the event in its implementation.
3. In class LCL_CARRIER, define a handler method for the event that you just defined(recommended name: ON_AIRPLANE_CREATED).
4. Implement the handler method so that the new airplane is added to the airplane list of thecarrier.
Hint:You can do that either directly or by calling the existing methodADD_AIRPLANE. In both cases, you should make sure that the same airplane
cannot be added to the list again. Therefore, either delete methodADD_AIRPLANE or make it private.
5. Remove all calls of ADD_AIRPLANE from your main program.
6. Register the new handler method, so that the airline enters every airplane that wascreated after itself in the list.
© Copyright . All rights reserved. 251
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 264/505
Note:Although this model is unrealistic, we will use it for the time being. You cancreate a different rule for entering the airplane later.
7. Where could the SET HANDLER statement be executed in the example given? Could thisalso be done from the main program?
8. Observe the execution of the program in the ABAP Debugger .
9. What would the syntax have to be in this case?
Task 2
Define an event for the creation of a vehicle. Trigger and handle it so that the reference to thevehicle is entered into the car rental company’s list of vehicles.
1. Remove all calls of ADD_VEHICLE from your main program.
2. Define the public event VEHICLE_CREATED in class LCL_VEHICLE and fire the event in theimplementation of the constructor.
3. In class LCL_RENTAL, define and implement a handler method for the event that you justdefined (recommended name: ON_VEHICLE_CREATED).
4. Register the new handler method, so that the car rental company enters every vehicle thatwas created after itself in the list.
Note:Although this model is unrealistic, we will use it for the time being. A differentrule for entering the vehicles could be created later.
5. Observe the execution of the program in the ABAP Debugger .
Unit 5: Object-Oriented Events
252 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 265/505
Unit 5Solution 14
237Implement Events in Local Classes
Business Example
Include airplane and vehicle references in the airline and the car rental company’s lists. Thisprocess is to be event-controlled.
Template:
SAPBC401_INT_S3
Solution:
SAPBC401_EVE_S1
Task 1
Define an event for the creation of an airplane. Trigger and handle it so that the reference tothe airplane is entered into the airline’s list of airplanes.
1. Complete your program ZBC401_##_MAIN (## is your two-digit group number) or copythe template program.
Identify the class that is suitable for triggering the event and the class that you should usefor handling the event. Use your UML diagram if necessary.
a) Carry out this step in the usual manner. For more information refer to the SAP Library.
2. Define the public event AIRPLANE_CREATED in class LCL_AIRPLANE. Choose a suitablemethod of LCL_AIRPLANE and fire the event in its implementation.
a) See source code extract from the model solution.
3. In class LCL_CARRIER, define a handler method for the event that you just defined(recommended name: ON_AIRPLANE_CREATED).
a) See source code extract from the model solution.
4. Implement the handler method so that the new airplane is added to the airplane list of thecarrier.
Hint:You can do that either directly or by calling the existing methodADD_AIRPLANE. In both cases, you should make sure that the same airplanecannot be added to the list again. Therefore, either delete methodADD_AIRPLANE or make it private.
a) See source code extract from the model solution.
5. Remove all calls of ADD_AIRPLANE from your main program.
a) See source code extract from the model solution.
© Copyright . All rights reserved. 253
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 266/505
6. Register the new handler method, so that the airline enters every airplane that wascreated after itself in the list.
Note:Although this model is unrealistic, we will use it for the time being. You can
create a different rule for entering the airplane later.
a) See source code extract from the model solution.
7. Where could the SET HANDLER statement be executed in the example given? Could thisalso be done from the main program?
Either in the constructor of LCL_CARRIER or in the main program after the creation of theLCL_CARRIER but before the creation of the first airplane.
8. Observe the execution of the program in the ABAP Debugger .
a) Carry out this step in the usual manner. Additional information is available in the SAPLibrary.
9. What would the syntax have to be in this case?
SET HANDLER go_carrier->on_airplane_created FOR ALL INSTANCES.
Task 2
Define an event for the creation of a vehicle. Trigger and handle it so that the reference to thevehicle is entered into the car rental company’s list of vehicles.
1. Remove all calls of ADD_VEHICLE from your main program.
a) See source code extract from the model solution.
2. Define the public event VEHICLE_CREATED in class LCL_VEHICLE and fire the event in theimplementation of the constructor.
a) See source code extract from the model solution.
3. In class LCL_RENTAL, define and implement a handler method for the event that you justdefined (recommended name: ON_VEHICLE_CREATED).
a) See source code extract from the model solution.
4. Register the new handler method, so that the car rental company enters every vehicle thatwas created after itself in the list.
Note:Although this model is unrealistic, we will use it for the time being. A differentrule for entering the vehicles could be created later.
a) See source code extract from the model solution.
5. Observe the execution of the program in the ABAP Debugger .
a) Carry out this step in the usual manner. Additional information is available in the SAPLibrary.
Unit 5: Object-Oriented Events
254 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 267/505
LESSON SUMMARYYou should now be able to:
● Implement event-controlled method calls
● Trigger and handle events
● Register for events
● Explain visibility sections in event handling
Lesson: Implementing Events in Local Classes
© Copyright . All rights reserved. 255
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 268/505
Unit 5Lesson 2
240Implementing Events in Local Interfaces
LESSON OVERVIEWThis lesson explains the implementation of events in local interfaces.
Business Example
As a developer, implement events in local classes of the airplane. For this reason, you requirethe following knowledge:
● An understanding of events
● An understanding of interfaces
● An understanding of implementing events in local interfaces
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement events in local interfaces
Implement Event in a Local InterfaceEvents can be defined as interface components. Triggering and handling events are done thesame way as in classes. To implement event handling for Interfaces, we need to:
● Define events in interfaces
● Trigger interface events in implementing classes
● Handle interface events
● Register event handling
How to Implement an Event in a Local InterfaceTo finish the discussion of event handling, you should demonstrate the definition of an eventPARTNER_CREATED in interface LIF_PARTNER and how it is handled inLCL_TRAVEL_AGENCY. Emphasize that there is no syntax check, which ensures that allimplementing classes actually raise the event. If there is enough time, let the participantsrepeat this in the optional second exercise of this lesson.
256 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 269/505
Unit 5Exercise 15
241Implement Event Handling for Interfaces
Business Example
Airline and car rental company references are to be entered into the travel agent’s list. Thisprocess is to be event-controlled. Be sure to create your program so that it can be easilyextended to manage additional business partners of the travel agent in the future.
Template:
SAPBC401_EVE_S1
Solution:
SAPBC401_EVE_S2
Define an event for the creation of a business partner. Trigger and handle it so that thereference to the business partner is entered into the travel agent’s list of partners.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise (where ## is your two-digit group number).
2. Remove the calls of the method ADD_PARTNER from your main program.
Note:The entry of a business partner reference into the travel agent’s list is to beevent-controlled.
3. If necessary, examine your UML diagram. Which class or interface should define theevent? Which class or interface should trigger it? Which class or interface should handleit?
If applicable, illustrate the relationships in your UML diagram.
4. Define the event PARTNER_CREATED and trigger it using a suitable method in all classesthat implement the interface.
5. Remove the method ADD_PARTNER in the class LCL_TRAVEL_AGENCY. Replace it by ahandler method for the event that you just defined (suggested name:ON_PARTNER_CREATED).
6. Register the new handler method, so that the travel agency enters every business partnerthat was created after itself into the list.
Note:Although this model is unrealistic, we will use it for the time being. A differentrule for entering the business partner can be created later.
© Copyright . All rights reserved. 257
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 270/505
7. Observe the execution of the program in the ABAP Debugger .
Unit 5: Object-Oriented Events
258 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 271/505
Unit 5Solution 15
243Implement Event Handling for Interfaces
Business Example
Airline and car rental company references are to be entered into the travel agent’s list. Thisprocess is to be event-controlled. Be sure to create your program so that it can be easilyextended to manage additional business partners of the travel agent in the future.
Template:
SAPBC401_EVE_S1
Solution:
SAPBC401_EVE_S2
Define an event for the creation of a business partner. Trigger and handle it so that thereference to the business partner is entered into the travel agent’s list of partners.
1. Complete your ZBC401_##_MAIN program or copy the model solution from the previousexercise (where ## is your two-digit group number).
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
2. Remove the calls of the method ADD_PARTNER from your main program.
Note:The entry of a business partner reference into the travel agent’s list is to beevent-controlled.
a) See the source code extract from the model solution.
3. If necessary, examine your UML diagram. Which class or interface should define theevent? Which class or interface should trigger it? Which class or interface should handleit?
If applicable, illustrate the relationships in your UML diagram.
a) Speak to your instructor if you have any questions.
4. Define the event PARTNER_CREATED and trigger it using a suitable method in all classesthat implement the interface.
a) See the source code extract from the model solution.
5. Remove the method ADD_PARTNER in the class LCL_TRAVEL_AGENCY. Replace it by ahandler method for the event that you just defined (suggested name:ON_PARTNER_CREATED).
a) See the source code extract from the model solution.
6. Register the new handler method, so that the travel agency enters every business partner
that was created after itself into the list.
© Copyright . All rights reserved. 259
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 272/505
Note:Although this model is unrealistic, we will use it for the time being. A differentrule for entering the business partner can be created later.
a) See the source code extract from the model solution.
7. Observe the execution of the program in the ABAP Debugger .
a) Carry out this step in the usual manner. Additional information is available in the SAPLibrary.
Unit 5: Object-Oriented Events
26 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 273/505
LESSON SUMMARYYou should now be able to:
● Implement events in local interfaces
Lesson: Implementing Events in Local Interfaces
© Copyright . All rights reserved. 261
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 274/505
Unit 5: Object-Oriented Events
262 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 275/505
Unit 5
247Learning Assessment
1. Which of the following is not defined as interface component?
Choose the correct answer.
X A Attributes
X B Methods
X C Events
X D Classes
2. Which of the following statement is used to define events within a class?
Choose the correct answer.
X A CLASS-EVENTS
X B RAISE EVENT
X C EVENTS
X D FOR EVENTS
3. Which of the following statement is used to trigger events?
Choose the correct answer.
X A CLASS-EVENTS
X B RAISE EVENT
X C EVENTS
X D FOR EVENTS
4. You can trigger static events only in static methods.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 263
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 276/505
5. Which of the following is specified by the definition of the handler method?
Choose the correct answer.
X A which method will react to which event of which class
X B which event the reaction will trigger
X C which instance(s) will perform the reaction
6. Which of the following is always carried out using the trigger?
Choose the correct answer.
X A Instance Event
X B Deregistration
X C Static Event
X D Registration
7. Every object or class that has defined event does not have handler table.
Determine whether this statement is true or false.
X True
X False
8. Which of the following is used to handle the visibility of the event within the class or itssubclasses?
Choose the correct answer.
X A Public
X B Protected
X C Private
9. All implementing classes will raise the events, if that there is no syntax check.
Determine whether this statement is true or false.
X True
X False
Unit 5: Learning Assessment
264 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 277/505
Unit 5
249Learning Assessment- Answers
1. Which of the following is not defined as interface component?
Choose the correct answer.
X A Attributes
X B Methods
X C Events
X D Classes
2. Which of the following statement is used to define events within a class?
Choose the correct answer.
X A CLASS-EVENTS
X B RAISE EVENT
X C EVENTS
X D FOR EVENTS
3. Which of the following statement is used to trigger events?
Choose the correct answer.
X A CLASS-EVENTS
X B RAISE EVENT
X C EVENTS
X D FOR EVENTS
© Copyright . All rights reserved. 265
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 278/505
4. You can trigger static events only in static methods.
Determine whether this statement is true or false.
X True
X False
5. Which of the following is specified by the definition of the handler method?
Choose the correct answer.
X A which method will react to which event of which class
X B which event the reaction will trigger
X C which instance(s) will perform the reaction
6. Which of the following is always carried out using the trigger?
Choose the correct answer.
X A Instance Event
X B Deregistration
X C Static Event
X D Registration
7. Every object or class that has defined event does not have handler table.
Determine whether this statement is true or false.
X True
X False
8. Which of the following is used to handle the visibility of the event within the class or itssubclasses?
Choose the correct answer.
X A Public
X B Protected
X C Private
Unit 5: Learning Assessment- Answers
266 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 279/505
9. All implementing classes will raise the events, if that there is no syntax check.
Determine whether this statement is true or false.
X True
X False
Unit 5: Learning Assessment- Answers
© Copyright . All rights reserved. 267
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 280/505
Unit 5: Learning Assessment- Answers
268 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 281/505
UNIT 6 Object-Oriented RepositoryObjects
Lesson 1
Creating Global Classes 270Exercise 16: Implement a Global Class 281
Lesson 2
Defining and Implementing Global Interfaces 286
Exercise 17: Import and Implement a Global Interface 289
Lesson 3
Implementing Inheritance in Global Classes 294Exercise 18: Implement Inheritance in Global Classes 301
UNIT OBJECTIVES● Create global classes
● Test global classes
● Use global classes
● Define and implement global interfaces
● Import local classes and interfaces
● Generate UML diagrams for global classes
● Implement inheritance in global classes
● Handle global classes
● Use the refactoring assistant
© Copyright . All rights reserved. 269
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 282/505
Unit 6Lesson 1
254Creating Global Classes
LESSON OVERVIEWThis lesson explains the method of creating global classes.
Business Example
As a developer, you must create a global class for an airplane class that can be accessed byall. For this reason, you require the following knowledge:
● An understanding of global classes
● An understanding of how to use global classes
● An understanding of how to test global classes
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Create global classes
● Test global classes
● Use global classes
Definition of Global Classes
Be sure to explain the correct use of the Class Builder in detail. In addition to thepresentation, you should show all of the steps in a separate demonstration class. Forinstance, you can demonstrate how to create a global class for shippings and then have theparticipants build the class for hotels in the exercise.
A further idea will be to let the participants discover and perform inheritance, redefinition,and definition of the constructor themselves in the Class Builder . This was huge motivationsin the first teach of the course.
Note:A large number of screenshots and screen illustrations are used in the lesson.Note that the appearance of some of the icons or menus depends on the releaselevel.
As with subroutines, use local classes or interfaces only within the program in which they aredefined and implemented. The CLASS statement is a local, declarative statement in theprogram. Just as the TYPES statement defines local data types, the CLASS statement defines
local object types. In both cases, whether or not the source text is stored separately in includeprograms is irrelevant.
27 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 283/505
On the other hand, global classes or global interfaces are individual repository objects with allof the normal attributes such as active integration, versioning, transport system, and so on.The namespace convention (Y*, Z*, or a special customer namespace) is the same as thatname used for the namespace of other repository objects.
Therefore, a special maintenance tool is available in the ABAP Workbench as of SAP R/3 4.6A
that is the Class Builder .Where doubts arise, you are advised to use the Quickinfo . It is the explanatory text thatappears when you place the cursor over an icon and leave it there for a short time.
Creating Global Classes in the Object Navigator
Figure 103: Creating Global Classes in the Object Navigator
As with other repository objects, the separate navigation area of the Object Navigator makesit the ideal development tool for all repository objects. It also supports the Class Builder . Aswith other repository objects, the easiest way to create a new global class is to use thecontext menu in the navigation area. To do so, first select the package node or select the classnode itself within a package.
A dialog box asks you to make further attributes for the new class. Do not change the defaultattributes at this point. You learn about the different settings and their effects later. Do thesame when creating global classes.
The global class or global interface is then displayed in the Class Builder table in the editorarea of the Object Navigator.
Since it has been mentioned, some of the icons and menus could be different depending onthe release level. When you are learning to work in the Class Builder , use of the Quickinfo isrecommended.
Lesson: Creating Global Classes
© Copyright . All rights reserved. 271
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 284/505
Definition of Attributes in Global Class
Figure 104: Definition of Attributes
Choose the Attributes tab to open the list of all attribute definitions in the class. You candefine new attributes here.
You can use the input help when you are defining the type attributes. Remember to usemeaningful short descriptions.
Create Methods in Global Class
Figure 105: Definition of Methods
Unit 6: Object-Oriented Repository Objects
272 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 285/505
Choose the Methods tab to open the list of all method definitions in the class. You can definenew methods here. You can use the input help when defining the attributes. Remember to usemeaningful short descriptions.
There are separate editor windows for the signature and the implementation.
Caution:Finding the signature of methods is often overlooked, or even forgotten, in theexercises. Demonstrate this several times.
Choose the Constructor to define an instance constructor. The constructor name is chosenautomatically and the selection possibilities in the editor window for the signature arerestricted appropriately.
Hint:Methods can be transported separately.
Definition of Method Signatures
Figure 106: Definition of Method Signatures
In the method list, select a method and choose the Parameter pushbutton to go to thesignature maintenance. You can define new formal parameters here. You can use the inputhelp when defining the attributes. Remember to use meaningful short descriptions.
You can scroll between the signatures using the Previous Method or Next Methodspushbutton. Choose the Methods pushbutton to return to the method list.
Lesson: Creating Global Classes
© Copyright . All rights reserved. 273
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 286/505
Implementation of Methods
Figure 107: Implementation of Methods
In the method list, select a method by double-clicking it or, if a method is already selected,choose the Source code to go to the source text maintenance. You can implement themodifications here.
Hint:
You can display the method’s signature by choosing the relevant pushbutton.
Unit 6: Object-Oriented Repository Objects
274 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 287/505
Displaying the Method Definition
Figure 108: Displaying the Method Definition
Choose Goto → Method definition if you want to change the attributes of your method duringthe implementation. You can define a handler method. For example, you do this by way of theProperties tab header in the dialog box.
Definition of Components Using the Navigation Area
Figure 109: Definition of Components Using the Navigation Area
You can also define attributes, methods, or events in the context menu of the ObjectNavigator’s navigation area. The properties are then maintained in a dialog box, and not in thetable.
Lesson: Creating Global Classes
© Copyright . All rights reserved. 275
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 288/505
Hint:Print selected portions of the source text using Class → Print or Method → Print .
Class Builder Testing Environment
Figure 110: The Class Builder Testing Environment
You can test active global classes.
You temporarily allocate the templates of the class. Allocate static ones immediately, whileinstance components are allocated when you choose the Instance pushbutton.
The system only lists the public components. Methods can be tested using the Call methodpushbutton.
Steps to trigger events in a class are as follows:1. Select an event.
2. Choose Handler . This handler registers a standard method for the event.
3. Call a method in which the event trigger was implemented.
The event that was triggered and all of the exported actual parameters are displayed in a list.
Demonstration: How To Implement a Global Class
To demonstrate how to implement a global class, implement suitable parts of programSAPBC401_GCL_D1.
Unit 6: Object-Oriented Repository Objects
276 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 289/505
Usage of Global Classes in the ABAP Editor
Figure 111: Separation of Navigation and Editing Areas in the Object Navigator
Be sure to demonstrate the following editing possibilities, ideally using the globaldemonstration class that you just created.
Show both possibilities of using Drag & Drop and the Pattern pushbutton.
Like other repository objects, global classes and interfaces are added in the navigation area ofthe OBJECT-NAVIGATOR. This way, the discussed advantages also apply to working withglobal classes and interfaces.
Object Instantiation Using Drag and Drop
Figure 112: Object Instantiation Using Drag and Drop
Lesson: Creating Global Classes
© Copyright . All rights reserved. 277
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 290/505
In the navigation area, select a class name and drag it to the editing area by holding down theleft mouse pushbutton. This action creates a CREATE OBJECT statement. Then, add thereference variable and the actual parameters, if applicable, to the statement.
Alternatively, you can also choose the Pattern pushbutton. The CREATE OBJECT statement isunder ABAP Objects Pattern . You can generate the statement using the input help.
Method Calls Using Drag and Drop
Figure 113: Method Calls Using Drag and Drop
In the navigation area, select a method name and drag it to the editing area by holding downthe left mouse pushbutton. This action creates a CREATE METHOD statement. Then, add thereference variable and the actual parameters, if applicable, to the statement.
Alternatively, you can also choose the Pattern pushbutton. The CALL METHOD statement isunder ABAP Objects Pattern . You can generate the statement using the input help.
Note:As of SAP NW AS 7.0 you can convert to functional modern writing style whengenerating method calls. Choose Utilities → Settings → Pattern and select the
Functional Writing Style for Call Method checkbox.
Your demonstration program could now look similar to program SAPBC401_GCL_D1.
Its recommended that you let the participants do the first exercise of this lesson.
Demonstration: How to Use a Global Class
To demonstrate how to use a global class, implement suitable parts of program
SAPBC401_GCL_D1.
Unit 6: Object-Oriented Repository Objects
278 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 291/505
Lesson: Creating Global Classes
© Copyright . All rights reserved. 279
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 292/505
Unit 6: Object-Oriented Repository Objects
28 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 293/505
Unit 6Exercise 16
263Implement a Global Class
Business Example
You want to create a global class to represent hotels.
Template:
SAPBC401_EVE_S2 (main program)
Solution:
SAPBC401_GCL_S1 (main program)CL_HOTEL (global class)
Task 1
Create a global class for hotels
1. Create the global class ZCL_##_HOTEL (## is your two-digit group number).
2. Define the following attributes in the class:
Attribute Name Type Description
C_POS_1 of the type I As a private constant with
value 30.MV_NAME of the type STRING As a private instance
attribute.
MV_BEDS of the type I As a private instanceattribute.
GV_N_O_HOTELS of the type I As a private static attribute.
Maintain the short texts.
3. Define the following methods in the class:
Method Name Method Description
CONSTRUCTOR Instance constructor for setting the privateattributes with the import parametersIM_NAME and IM_BEDS
DISPLAY_ATTRIBUTES Instance method for displaying attributes inan ABAP list
DISPLAY_N_O_HOTELS Static method to display the number ofcreated hotel instances in an ABAP list
4. Use the constant defined before to align the output of the values in a column.
© Copyright . All rights reserved. 281
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 294/505
Maintain the short texts.
Task 2
Check your work.
1. Activate your class.
2. Test your class in the Class Builder’ s testing environment.
Task 3
Create an instance of your global class for hotels in your main program.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the template program.
2. Define a reference variable, specify your global hotel class as the type, and create an
instance.3. If you have not done the optional exercise, where you add business partners to the travel
agency through event handling, try to call method ADD_PARTNER for the hotel.
4. Why can the hotel not yet be integrated into the list of travel agency of business partners?
5. Could the local interface LIF_PARTNER be implemented in the global class for hotels?
Unit 6: Object-Oriented Repository Objects
282 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 295/505
Unit 6Solution 16
265Implement a Global Class
Business Example
You want to create a global class to represent hotels.
Template:
SAPBC401_EVE_S2 (main program)
Solution:
SAPBC401_GCL_S1 (main program)CL_HOTEL (global class)
Task 1
Create a global class for hotels
1. Create the global class ZCL_##_HOTEL (## is your two-digit group number).
a) Follow the processes as outlined in the relevant section of this lesson.
2. Define the following attributes in the class:
Attribute Name Type Description
C_POS_1 of the type I As a private constant withvalue 30.
MV_NAME of the type STRING As a private instanceattribute.
MV_BEDS of the type I As a private instanceattribute.
GV_N_O_HOTELS of the type I As a private static attribute.
Maintain the short texts.
a) Follow the processes as outlined in the relevant section of this lesson.
3. Define the following methods in the class:
Method Name Method Description
CONSTRUCTOR Instance constructor for setting the privateattributes with the import parametersIM_NAME and IM_BEDS
DISPLAY_ATTRIBUTES Instance method for displaying attributes inan ABAP list
© Copyright . All rights reserved. 283
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 296/505
Method Name Method Description
DISPLAY_N_O_HOTELS Static method to display the number ofcreated hotel instances in an ABAP list
4. Use the constant defined before to align the output of the values in a column.
Maintain the short texts.
a) Follow the processes as outlined in the relevant section of this lesson.
Task 2
Check your work.
1. Activate your class.
a) Carry out this step in the usual manner. Additional information is available in the SAPLibrary.
2. Test your class in the Class Builder’ s testing environment.
a) Follow the processes as outlined in the relevant section of this lesson.
Task 3
Create an instance of your global class for hotels in your main program.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the template program.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
2. Define a reference variable, specify your global hotel class as the type, and create aninstance.
a) See source text excerpt from the model solution.
3. If you have not done the optional exercise, where you add business partners to the travelagency through event handling, try to call method ADD_PARTNER for the hotel.
a) Do this exactly in the same way as you already do it for the carrier and the car rentalcompany.
4. Why can the hotel not yet be integrated into the list of travel agency of business partners?
The global class for hotels does not implement the interface that is used by the travelagency class.
5. Could the local interface LIF_PARTNER be implemented in the global class for hotels?
No, global classes can only implement global interfaces. Therefore, the local interface hasto be replaced with a global one. This is done in the next exercise.
Unit 6: Object-Oriented Repository Objects
284 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 297/505
LESSON SUMMARYYou should now be able to:
● Create global classes
● Test global classes
● Use global classes
Lesson: Creating Global Classes
© Copyright . All rights reserved. 285
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 298/505
Unit 6Lesson 2
268Defining and Implementing Global Interfaces
LESSON OVERVIEWThis lesson explains how to define and implement global interfaces.
Business Example
As a developer, you need to create a global interface so that other developers in yourorganization can use the same interface and implement it in their own ways in their classes.
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Define and implement global interfaces
● Import local classes and interfaces
Definition of Global Interfaces
Figure 114: Defining Global Interfaces
If you want the participants to create the global interface manually, you can let them do theexercise on the global interfaces. However, we recommend you do this later so that theparticipants can import the local interface into the class library.
286 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 299/505
You create global interfaces in a similar way to how you create global classes. Proceed asnormal, using the right mouse button in the Object Navigator . The naming convention is IF_ forSAP interfaces and ZIF_ or YIF_ for user-defined interfaces.
Implementation of Global Interfaces
If you want the participants do create the global interface manually, you can let them do theexercise on the global interfaces here. However, it is recommended that you do this later sothat the participants can import the local interface into the class library.
If you want to include a global interface in your global class, you must enter the name of theinterface on the Interfaces tab.
Once you have done that, all of the interface’s components automatically appear under therelevant tabs according to the naming convention and the interface resolution operator. In theexample, the ZIF_00_PARTNER global interface is incorporated in the DISPLAY_PARTNERmethod. You can implement the method simply by double-clicking on the method name.
Import of Local Classes and Interfaces
Figure 115: Importing a Local Program Class
The procedure is an easy way to make global copies of local classes and local interfaces.
Hint:The function to copy local classes to global classes cannot be used from withinOBJECT-NAVIGATOR.
To Import Local Classes and Interfaces
The steps to import local classes and interfaces are as follows:
Lesson: Defining and Implementing Global Interfaces
© Copyright . All rights reserved. 287
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 300/505
1. On the SAP Easy Access screen, choose Tools → ABAPWorkbench → Development → Class Builder or call transaction SE24 .
2. On the Class Builder: Initial Screen , choose Object type → Import → Local programclasses .
3. In the Import from Program dialog box, enter the name of the main program and, if thelocal classes and interfaces were defined within include programs, select Expand includecheckbox.
4. Choose the Display Classes/Interfaces pushbutton.
5. Enter names for the global classes and interfaces that you want to create.
6. Remember the customer namespace, if applicable.
7. Choose the global classes and interfaces that you want to create and choose the Importpushbutton.
Demonstration: How to Import Local Classes and Interfaces
To demonstrate how to import local classes and interfaces, implement the steps mentionedin the procedure To Import Local Classes and Interfaces.
Unit 6: Object-Oriented Repository Objects
288 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 301/505
Unit 6Exercise 17
271Import and Implement a Global Interface
Business Example
Add a hotel as a new business partner in your program for managing a travel agency’sbusiness partners.
Template:
SAPBC401_EVE_S2 (program)
CL_HOTEL (global class)
Solution:
SAPBC401_GCL_S1 (program)
CL_HOTEL2 (global class)
IF_PARTNER (global interface)
Task 1
Create a global interface for generalized access to business partner instances.
1. If applicable, change the interface name in your UML diagram to ZIF_##_PARTNERS. (##is your two-digit group number).
2. Create the global interface ZIF_##_PARTNER.
Define the instance method DISPLAY_PARTNER in your global interface. If the localinterface contains the event PARTNER_CREATED define the event also in your globalinterface.
Hint:Instead of creating the global interface manually you can import the localinterface from your program ZBC401_##_MAIN or the template program.
Task 2
Create a global interface for generalized access to business partner instances.
Replace the local interface in your main program with the global one.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the template program.
2. Completely remove the definition of the local interface.
3. Adapt all places where the local interface was used so that the global interface is used andimplemented instead.
© Copyright . All rights reserved. 289
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 302/505
Hint:To reduce the typing efforts take advantage of the search or replacefunctionality of the ABAP Editor .
Task 3
Have your hotel class implement the interface and test your program.
1. Complete your global class ZCL_##_HOTEL (where ## is your two-digit group number) orcopy the template class.
2. In your main program, replace the reference to the template class with a reference to yourown class.
3. If necessary, add the class ZCL_##_HOTEL to your UML diagram. It should implement theinterface method DISPLAY_PARTNER and trigger the instance eventPARTNER_CREATED. Draw the relationships in your diagram.
4. Declare the interface as an implemented interface in your hotel class.
5. Implement the interface method in such a way that the hotel’s DISPLAY_ATTRIBUTESinstance method is called.
6. Activate the global class and your program. Run your program. If you have doneeverything correctly, the hotel attributes should now be displayed on the list too.Otherwise, debugging is the best way of analyzing any errors that may have occurredhere.
Unit 6: Object-Oriented Repository Objects
29 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 303/505
Unit 6Solution 17
273Import and Implement a Global Interface
Business Example
Add a hotel as a new business partner in your program for managing a travel agency’sbusiness partners.
Template:
SAPBC401_EVE_S2 (program)
CL_HOTEL (global class)
Solution:
SAPBC401_GCL_S1 (program)
CL_HOTEL2 (global class)
IF_PARTNER (global interface)
Task 1
Create a global interface for generalized access to business partner instances.
1. If applicable, change the interface name in your UML diagram to ZIF_##_PARTNERS. (##is your two-digit group number).
a) Speak to your instructor if you have any questions.
2. Create the global interface ZIF_##_PARTNER.
Define the instance method DISPLAY_PARTNER in your global interface. If the localinterface contains the event PARTNER_CREATED define the event also in your globalinterface.
Hint:Instead of creating the global interface manually you can import the localinterface from your program ZBC401_##_MAIN or the template program.
a) Follow the processes as outlined in the relevant section of this lesson. Speak to yourinstructor if you have any questions.
Task 2
Create a global interface for generalized access to business partner instances.
Replace the local interface in your main program with the global one.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number) orcopy the template program.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
© Copyright . All rights reserved. 291
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 304/505
2. Completely remove the definition of the local interface.
a) See source text excerpt from the model solution.
3. Adapt all places where the local interface was used so that the global interface is used andimplemented instead.
Hint:To reduce the typing efforts take advantage of the search or replacefunctionality of the ABAP Editor .
a) See source text excerpt from the model solution.
Task 3
Have your hotel class implement the interface and test your program.
1. Complete your global class ZCL_##_HOTEL (where ## is your two-digit group number) orcopy the template class.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
2. In your main program, replace the reference to the template class with a reference to yourown class.
a) See source text excerpt from the model solution.
3. If necessary, add the class ZCL_##_HOTEL to your UML diagram. It should implement theinterface method DISPLAY_PARTNER and trigger the instance eventPARTNER_CREATED. Draw the relationships in your diagram.
a) Speak to your instructor if you have any questions.
4. Declare the interface as an implemented interface in your hotel class.
a) Follow the processes as outlined in the relevant section of this lesson.
5. Implement the interface method in such a way that the hotel’s DISPLAY_ATTRIBUTESinstance method is called.
a) Follow the processes as outlined in the relevant section of this lesson.
6. Activate the global class and your program. Run your program. If you have doneeverything correctly, the hotel attributes should now be displayed on the list too.Otherwise, debugging is the best way of analyzing any errors that may have occurredhere.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
Unit 6: Object-Oriented Repository Objects
292 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 305/505
LESSON SUMMARYYou should now be able to:
● Define and implement global interfaces
● Import local classes and interfaces
Lesson: Defining and Implementing Global Interfaces
© Copyright . All rights reserved. 293
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 306/505
Unit 6Lesson 3
276Implementing Inheritance in Global Classes
LESSON OVERVIEWThis lesson explains how to generate UML diagrams for global classes.
Business Example
As a developer, you need to generate UML diagram for an airplane class.
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Generate UML diagrams for global classes
● Implement inheritance in global classes
● Handle global classes
● Use the refactoring assistant
Generation of UML Diagrams for Global Classes
Figure 116: Generate a UML Diagram for Package
As of SAP NetWeaver 7.0 EhP2, the Class Builder can generate UML diagrams for existingcoding. This function is restricted only to global classes and not local classes. But it can
include objects from ABAP Dictionary .
294 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 307/505
The figure explains how to start the functionality for a complete package. On a pop-up windowyou can add a selection of objects and specify which details you want to see on the diagram.
Demonstration: How to Generate an UML Diagrams for Global Classes of a Package
To illustrate this, you can use either your own development package or Package
BC401_MODEL , which is a sub-package of BC401 package. It contains global copies of thelocal classes developed so far.
Definition of Inheritance in Global Classes
Figure 117: Defining an Inheritance Relationship
You set out the inheritance relationships between global classes on the Properties tab.
You can specify a superclass after you choose Superclass pushbutton. In the example, thesubclass ZCL_CARGO_PLANE_00 will inherit from superclass ZCL_AIRPLANE_00.
Lesson: Implementing Inheritance in Global Classes
© Copyright . All rights reserved. 295
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 308/505
Redefinition of a Method in Global Class
Figure 118: Redefining an Inherited Method
To redefine an inherited method, select the relevant method in the list and choose theRedefine pushbutton. Alternatively, you can use the context menu in the navigation area.
Note:Note that the appearance of some of the icons or menus depends on the releaselevel. The icon for redefining methods is an example of this.
Hint:To define the constructor in the subclass, click on the CONSTRUCTORpushbutton in the application toolbar. The system then proposes transferring thesignature of the superclass constructor. This is helpful when you want to createthe subclass constructor. You may have to add some parameters here. Similarly,you will also find the call for the superclass.
Unit 6: Object-Oriented Repository Objects
296 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 309/505
Definition of Local Types in Global Classes
Figure 119: Defining a Local Type
You can define local types in global classes. This includes local classes in particular.
Technically, you are not defining a class within a class, but a class that is local in therepository object of the global class.
All components of the global class have access to these local types, but they are encapsulatedif you try to access them from outside.
The same applies for local interfaces in global classes.
To edit the implementation parts of these local classes, choose the Impl pushbutton for localclass implementations.
Display of Class Components
Figure 120: Structured Display of Inherited Components
Lesson: Implementing Inheritance in Global Classes
© Copyright . All rights reserved. 297
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 310/505
To improve your understanding of inheritance and interface components, you can set theGroup by Classes and Interfaces flag in the User-Specific Settings for the Class Builder . Thesystem will then display the components of the global class in a group.
Sorting the Component Display of Global Classes
Figure 121: Sorting the Component Display of Global Classes
You can also sort all components by five criteria in three levels. To do sort all components,display the appropriate dialog box by choosing the Sort pushbutton.
The Refactoring Assistant
Figure 122: Working with the Refactoring Assistant
In an ideal world, all classes, interfaces, and the associations between them would bemodeled completely using UML diagrams before developers began implementing them.However, in some cases, the model needs to be adapted during the implementation phase.The Refactoring Assistant offers a range of user-friendly options for you to change repository
Unit 6: Object-Oriented Repository Objects
298 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 311/505
objects that you created previously. For example, you can use the Refactoring Assistant tomove the components of a class within the inheritance hierarchy. For a complete list of thefeatures in this tool, refer to the SAP Library . Working with the tool is simple, since it is basedon Drag and Drop dialogs.
Hint:The Tool Info pushbutton opens the SAP Library article about the Refactoring Assistant . There you can also find the descriptions about other abilities of thetool.
Generally, you do not adjust the implementation of methods, since you cannot know howmuch you will need to alter object references after making these changes.
To Move a Method Definition from a Global Class to a Global Interface
If your time schedule allows, you can perform the exercise on the Refactoring Assistant .
The steps to move a method definition from a global class to a global interface are asfollows:
1. Change to the editing mode of a global class that implements a global interface.
2. Choose Tools → Refactoring Assistant .
3. In the tree structure that appears, open the folder for the method you want to move andfor the target – in this case, the implemented interface.
4. Move the method to the interface.
5. Save your work.
6. You might also need to adapt statements calling the method in the source code.
7. Activate both the class and the interface.
Demonstration: How to Implement Inheritance in Global Classes
To demonstrate implement inheritance in global classes, use suitable parts of program
SAPBC401_GCL_D2.
Lesson: Implementing Inheritance in Global Classes
© Copyright . All rights reserved. 299
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 312/505
Unit 6: Object-Oriented Repository Objects
3 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 313/505
Unit 6Exercise 18
283Implement Inheritance in Global Classes
Business Example
You will practice working with the Refactoring Assistant .
Template:
CL_HOTEL2 (global class)
Solution:
CL_HOTEL 3 (global class)CL_HOTEL (global class)
Task 1
Define a global superclass for houses and have your hotel class inherit from it.
1. If necessary, add the class ZCL_##_HOUSE to your UML diagram. (## is your two-digitgroup number.)
It will define the attribute MV_NAME and the method DISPLAY_ATTRIBUTES.
The class ZCL_##_HOTEL will inherit from it. Draw the relationships in your diagram.
2. Create the global class ZCL_##_HOUSE and leave it empty.
Caution:Make sure you deselect the final checkbox. In the next lesson you’ll learn theexact meaning of this property.
Speak to your instructor if you have any questions.
3. Define an inheritance relationship to make ZCL_##_HOUSE the superclass andZCL_##_HOTEL the subclass.
Speak to your instructor if you have any questions.
Task 2
Move the general components of the ZCL_##_HOTEL class to the superclass.
1. Use the Refactoring Assistant to move the c_POS_1 constant, the MV_NAME attribute, theinstance constructor, and the DISPLAY_ATTRIBUTES method into the classZCL_##_HOUSE.
Speak to your instructor if you have any questions.
2. Adapt the signature and the implementation of the instance constructor in the superclass.
Speak to your instructor if you have any questions.
© Copyright . All rights reserved. 3 1
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 314/505
3. Adapt the implementation of the DISPLAY_ATTRIBUTES method in the superclass.
Speak to your instructor if you have any questions.
4. Define and implement the instance constructor for the superclass.
Speak to your instructor if you have any questions.
5. Redefine the DISPLAY_ATTRIBUTES method in the subclass.
Hint:To make constant C_POS_1 available in the implementation ofDISPLAY_ATTRIBUTES of the subclass, you have to change its visibility to atleast protected.
Speak to your instructor if you have any questions.
6. Observe the execution of the program in the ABAP Debugger .
Unit 6: Object-Oriented Repository Objects
3 2 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 315/505
Unit 6Solution 18
285Implement Inheritance in Global Classes
Business Example
You will practice working with the Refactoring Assistant .
Template:
CL_HOTEL2 (global class)
Solution:
CL_HOTEL 3 (global class)CL_HOTEL (global class)
Task 1
Define a global superclass for houses and have your hotel class inherit from it.
1. If necessary, add the class ZCL_##_HOUSE to your UML diagram. (## is your two-digitgroup number.)
It will define the attribute MV_NAME and the method DISPLAY_ATTRIBUTES.
The class ZCL_##_HOTEL will inherit from it. Draw the relationships in your diagram.
a) Speak to your instructor if you have any questions.
2. Create the global class ZCL_##_HOUSE and leave it empty.
Caution:Make sure you deselect the final checkbox. In the next lesson you’ll learn theexact meaning of this property.
a) Follow the processes as outlined in the relevant section of this lesson.
Speak to your instructor if you have any questions.
3. Define an inheritance relationship to make ZCL_##_HOUSE the superclass andZCL_##_HOTEL the subclass.a) Follow the processes as outlined in the relevant section of this lesson.
Speak to your instructor if you have any questions.
Task 2
Move the general components of the ZCL_##_HOTEL class to the superclass.
1. Use the Refactoring Assistant to move the c_POS_1 constant, the MV_NAME attribute, theinstance constructor, and the DISPLAY_ATTRIBUTES method into the class
ZCL_##_HOUSE.
© Copyright . All rights reserved. 3 3
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 316/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 317/505
LESSON SUMMARYYou should now be able to:
● Generate UML diagrams for global classes
● Implement inheritance in global classes
● Handle global classes
● Use the refactoring assistant
Lesson: Implementing Inheritance in Global Classes
© Copyright . All rights reserved. 3 5
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 318/505
Unit 6: Object-Oriented Repository Objects
3 6 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 319/505
Unit 6
289Learning Assessment
1. You should use local classes or interfaces only within the program in which they aredefined and implemented.
Determine whether this statement is true or false.
X True
X False
2. Which of the following are used to test the triggering of events in a class?
Choose the correct answers.
X A Select an event
X B Choose Handler
X C Call a class
3. You cannot convert to functional modern writing style when generating method calls as of
SAP NW AS 7.0.Determine whether this statement is true or false.
X True
X False
4. The naming convention for SAP interfaces is “ZIF_ or YIF_”.
Determine whether this statement is true or false.
X True
X False
5. An interface object can be used to call a method from the implementing class of theinterface.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 3 7
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 320/505
6. Which of the following is used to generate UML diagrams for existing coding?
Choose the correct answer.
X A Class Builder
X B Superclass
X C Methods
X D Interfaces
7. Which of the following pushbutton is used to redefine an inherited method?
Choose the correct answer.
X A CONSTRUCTOR
X B Redefine
X C Impl
8. Local type of the global class are not encapsulated and cannot be accessed from outside.
Determine whether this statement is true or false.
X True
X False
9. You cannot use the Refactoring Assistant to move the components of a class within theinheritance hierarchy.
Determine whether this statement is true or false.
X True
X False
Unit 6: Learning Assessment
3 8 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 321/505
Unit 6
291Learning Assessment- Answers
1. You should use local classes or interfaces only within the program in which they aredefined and implemented.
Determine whether this statement is true or false.
X True
X False
2. Which of the following are used to test the triggering of events in a class?
Choose the correct answers.
X A Select an event
X B Choose Handler
X C Call a class
3. You cannot convert to functional modern writing style when generating method calls as ofSAP NW AS 7.0.
Determine whether this statement is true or false.
X True
X False
4. The naming convention for SAP interfaces is “ZIF_ or YIF_”.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 3 9
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 322/505
5. An interface object can be used to call a method from the implementing class of theinterface.
Determine whether this statement is true or false.
X True
X False
6. Which of the following is used to generate UML diagrams for existing coding?
Choose the correct answer.
X A Class Builder
X B Superclass
X C Methods
X D Interfaces
7. Which of the following pushbutton is used to redefine an inherited method?
Choose the correct answer.
X A CONSTRUCTOR
X B Redefine
X C Impl
8. Local type of the global class are not encapsulated and cannot be accessed from outside.
Determine whether this statement is true or false.
X True
X False
9. You cannot use the Refactoring Assistant to move the components of a class within theinheritance hierarchy.
Determine whether this statement is true or false.
X True
X False
Unit 6: Learning Assessment- Answers
31 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 323/505
UNIT 7 ABAP Object-OrientedExamples
Lesson 1
Implementing ABAP List Viewer 312Exercise 19: Implement the ALV Grid Control 319Exercise 20: Implement a Popup with the ALV Grid Control 327
Lesson 2
Describing Business Add-Ins 339
UNIT OBJECTIVES
● Implement simple ABAP list viewer
● Implement double-click on ABAP list viewer
● Describe Business Add-Ins
© Copyright . All rights reserved. 311
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 324/505
Unit 7Lesson 1
294Implementing ABAP List Viewer
LESSON OVERVIEWThis lesson shows you how to implement ABAP list viewer (ALV).
Business Example
As an ABAP developer, your team requests you to create a report using the ALV grid control.
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement simple ABAP list viewer
● Implement double-click on ABAP list viewer
The ALV Grid ControlThe following topics will illustrate possible application areas of object-oriented ABAPprogramming and the use of SAP standard classes. As examples, there will be briefdiscussions of the ALV Grid Control in the context of the Control Framework and the BusinessAdd-Ins.
The SAP Control Framework is a collection of global classes and interfaces that you can useto add SAP Graphical User Interface (GUI) controls in your ABAP Objects programs,regardless of the platform. We will show you how to use SAP standard classes effectively withreference to the widely used ALV Grid Control.
Figure 123: The ALV Grid Control
312 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 325/505
The ALV Grid Control is a tool that you can use to display non-hierarchical lists in astandardized form. The list data displays in tables. It is very easy to work with as only very fewprogramming steps have to be carried out. The ALV Grid Control contains a number ofinteractive standard functions that users of lists often need, for example, print, export, and soon. As a developer, you have the option of hiding these standard functions. When required,you can adapt the implementations to fit the needs of your application. You can also add yourown functions to the application toolbar.
Including an ALV Grid Control Instance in a Dialog Program
Figure 124: Including an ALV Grid Control Instance in a Dialog Program
Container controls provide the technical connection between the screen and applicationcontrol. Generally, the application controls ALV Grid Control, Tree Control, Picture Control,and so on. These are always embedded in this Container Control, which, in turn, is connectedto the screen.
There are different types of container controls. However, they all incorporate fundamentalcontrol functions, such as scroll bars.
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 313
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 326/505
Usage of an ALV in a Screen Area
Figure 125: Displaying Application Data Using an ALV Grid Instance
Let us take a common case as an example, placing an ALV Grid Control in a screen area of afixed size.
You need to create an instance of each of the global classes CL_GUI_CUSTOM_CONTAINERand CL_GUI_ALV_GRID.
For normal display, the following programming steps are sufficient:1. Use the full screen editor of the Screen Painter to define a custom control area on your
screen.
2. Create an instance of the CL_GUI_CUSTOM_CONTAINER class, and transfer the name ofthe custom control area to the constructor.
3. Create an instance of the CL_GUI_GUI_ALV_GRID class, and transfer the reference to thecustom control instance to the constructor.
4. Call the SET_TABLE_FOR_FIRST_DISPLAY method of the Grid Control instance, andtransfer the internal standard table to it.
If the table has a global row type, you can transfer the name of this global structure to thesame method. Then, the Grid Control instance automatically creates the field catalog.
If you change the contents of the internal tables while the program is running, you only needto call the REFRESH_TABLE_DISPLAY method in the relevant dialog step to refresh thedisplay.
Demonstration: How to Implement Simple ABAP List Viewer
Be flexible while working on this section.
If the participants truly meet all prerequisites of this course, displaying data in the ALV GridControl is simply revision. If that is the case, consider demonstrating a different applicationcontrol or focus more on event handling with the SAP Grid Control.
Unit 7: ABAP Object-Oriented Examples
314 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 327/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 328/505
the example displayed, the booking data for the individual flight customers, or data on theaircraft, could also display for the flight data. Technically, this is executed by catching theDOUBLE_CLICK event with a handler method.
ALV Grid Control – Reacting to a Double-Click
Figure 127: ALV Grid Control – Reacting to a Double-Click
Here, a static handler method would in fact be easier and perfectly adequate. However, thiscould distract the participants from the actual topic. Be prepared for a discussion though.
The SET HANDLER statement is easily forgotten in the exercise for the ALV Grid. However,this is good training – the participants need to learn from their mistakes as well.
A handler method can be either a class method (static method) or an instance method of anobject. If a class method is defined as a handler method, no object of the handled class needsto be instantiated to use the method. To create a handler object for an event, first define aclass. This class has a public method in the PUBLIC SECTION that can react to an event.During the implementation of the handler method, define the source text that should be runwhen the event is triggered. The method receives the information that the event delivers fromthe mouse position when you double-click and creates an information message in the controlexample that displays the row and field of the mouse click.
Preferably, use the system to demonstrate how you can easily catch the double-click throughthis new handler class.
Unit 7: ABAP Object-Oriented Examples
316 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 329/505
Note:Extensive documentation about the SAP Control Framework is available. The SAPLibrary contains comprehensive descriptions of all classes and a completetutorial.
The Object Navigator also contains the Enjoy Demo Center, which makes it very easy to usestandard template programs. You can find it under Environment → Examples → ControlExamples .
Other courses cover individual elements of the SAP Control Framework.
SAP also offers a separate comprehensive course about dialog programming with the EnjoySAP controls. It covers all aspects, including complex programming techniques, such as theDrag and Drop functions.
It may be worth pointing out the relevant SAP course at this point (BC412).
Demonstration: How to Implement an Event Handler for the ALV Grid Control
Enhance the how to implement simple ALV demonstration by a handler for the double-clickevent.
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 317
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 330/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 331/505
Unit 7Exercise 19
299Implement the ALV Grid Control
Business Example
The user wants to see a list of flight connections in an ALV Grid Control. When you double-click a connection, the selected row number and column name should be displayed.
Template:
SAPBC401_ALV_T1
Solution:
SAPBC401_ALV_S1
Task 1
Create an ALV Grid Control, and react to double-click the ALV Grid Control.
Programming an ALV Grid Control and displaying the list of flight connections already storedin internal table GT_SPFLI.
1. Copy the template program SAPBC401_ALV_T1 to ZBC401_##_ALV.
2. In the main program, define the reference variables GO_CONTAINER and GO_ALV_GRIDrequired for the ALV Grid Control.
3. Analyze the already existing screen 100 – in particular, the name of the Custom ContainerControl Area, which is used as the basis for the ALV Grid Control.
Now implement the PBO module ALV_GRID. Use the reference variables to instantiate thetwo classes in this PBO module. Pay particular attention to the fact that the CREATEOBJECT is not called repeatedly when the PBO is executed repeatedly.
4. To display data in the ALV Grid Control, call the SET_TABLE_FOR_FIRST_DISPLAYmethod and transfer the internal table with the flight connection data and the name of theline type of that internal table.
5. Activate and test your program.
Caution:Note that you are working with a screen in this exercise and that you shouldalways activate all parts of the program. Therefore, do not forget to activatethe screen.
Task 2
Handle a double-click on the ALV Grid Control.
If the user double-clicks a row in the ALV Grid Control, the row number and column namewhere the user double-clicked should display in a message of type ‘I’.
© Copyright . All rights reserved. 319
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 332/505
1. Define a local class LCL_EVENT_HANDLER and in this class, define an instance method tohandle the DOUBLE_CLICK event that the ALV Grid Control triggered.
Note:The class LCL_EVENT_HANDLER only acts as a handler and, otherwise, does
not have any other functions.
Import parameters ES_ROW_NO and E_COLUMN into the handler method.
2. Implement the handler method. Send a message of type ‘I’ to output the row number andcolumn name the user clicked.
Hint:You can use message 010 of message class BC401.
3. Instantiate the handler class, and register the event handler method.
4. Activate and test your program.
REPORT sapbc401_alv_s1.
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_event_handler DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_event_handler DEFINITION. PUBLIC SECTION.
METHODS on_double_click FOR EVENT double_click OF cl_gui_alv_grid IMPORTING es_row_no e_column.ENDCLASS. "lcl_event_handler DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_event_handler IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_event_handler IMPLEMENTATION.
METHOD on_double_click.
MESSAGE i010(bc401) WITH es_row_no-row_id e_column-fieldname.
ENDMETHOD. "handler_methodENDCLASS. "lcl_event_handler IMPLEMENTATION
************** Types and Data Definitions ************************
TYPES: ty_spfli TYPE STANDARD TABLE OF spfli WITH NON-UNIQUE KEY carrid connid.
DATA: ok_code TYPE sy-ucomm.
DATA: go_handler TYPE REF TO lcl_event_handler, go_container TYPE REF TO cl_gui_custom_container, go_alv_grid TYPE REF TO cl_gui_alv_grid.
Unit 7: ABAP Object-Oriented Examples
32 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 333/505
DATA: gt_spfli TYPE ty_spfli.
START-OF-SELECTION.********************
SELECT * FROM spfli INTO TABLE gt_spfli.
CALL SCREEN '0100'.
*&---------------------------------------------------------------------**& Module STATUS_0100 OUTPUT*&---------------------------------------------------------------------*MODULE status_0100 OUTPUT. SET PF-STATUS 'DYNPROSTATUS'. SET TITLEBAR 'TITLE1'.ENDMODULE. " STATUS_0100 OUTPUT*&---------------------------------------------------------------------*
*& Module ALV_GRID OUTPUT*&---------------------------------------------------------------------*MODULE alv_grid OUTPUT.
*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data! IF go_container IS NOT BOUND. CREATE OBJECT go_container EXPORTING container_name = 'CONTAINER_1' EXCEPTIONS others = 6. IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.*** create object of class cl_gui_alv_grid to visualize data ! CREATE OBJECT go_alv_grid EXPORTING i_parent = go_container EXCEPTIONS others = 5. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
*** create handler instance and register handler method *******
CREATE OBJECT go_handler. SET HANDLER go_handler->on_double_click FOR go_alv_grid.
*** Call method to visualize data of internal table ************ CALL METHOD go_alv_grid->set_table_for_first_display EXPORTING i_structure_name = 'SPFLI' CHANGING it_outtab = gt_spfli EXCEPTIONS OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 321
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 334/505
ENDIF.
ENDIF.
ENDMODULE. " ALV_GRID OUTPUT*&---------------------------------------------------------------------*
*& Module USER_COMMAND_0100 INPUT*&---------------------------------------------------------------------*MODULE user_command_0100 INPUT.
CASE ok_code. WHEN 'BACK'. SET SCREEN 0. WHEN 'EXIT'. LEAVE PROGRAM. ENDCASE.
ENDMODULE. " USER_COMMAND_0100 INPUT
Unit 7: ABAP Object-Oriented Examples
322 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 335/505
Unit 7Solution 19
303Implement the ALV Grid Control
Business Example
The user wants to see a list of flight connections in an ALV Grid Control. When you double-click a connection, the selected row number and column name should be displayed.
Template:
SAPBC401_ALV_T1
Solution:
SAPBC401_ALV_S1
Task 1
Create an ALV Grid Control, and react to double-click the ALV Grid Control.
Programming an ALV Grid Control and displaying the list of flight connections already storedin internal table GT_SPFLI.
1. Copy the template program SAPBC401_ALV_T1 to ZBC401_##_ALV.
a) Carry out this step in the usual manner.
2. In the main program, define the reference variables GO_CONTAINER and GO_ALV_GRID
required for the ALV Grid Control.a) See the source code extract from the model solution or refer to the corresponding
slides about the ALV Grid Control.
3. Analyze the already existing screen 100 – in particular, the name of the Custom ContainerControl Area, which is used as the basis for the ALV Grid Control.
Now implement the PBO module ALV_GRID. Use the reference variables to instantiate thetwo classes in this PBO module. Pay particular attention to the fact that the CREATEOBJECT is not called repeatedly when the PBO is executed repeatedly.
a) See the source code extract from the model solution or refer to the correspondingslides about the ALV Grid Control. Speak to your instructor if you have any questions.
4. To display data in the ALV Grid Control, call the SET_TABLE_FOR_FIRST_DISPLAYmethod and transfer the internal table with the flight connection data and the name of theline type of that internal table.
a) See the source code extract from the model solution or refer to the correspondingslides about the ALV Grid Control. Speak to your instructor if you have any questions.
5. Activate and test your program.
© Copyright . All rights reserved. 323
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 336/505
Caution:Note that you are working with a screen in this exercise and that you shouldalways activate all parts of the program. Therefore, do not forget to activatethe screen.
a) Carry out this step in the usual manner.
Task 2
Handle a double-click on the ALV Grid Control.
If the user double-clicks a row in the ALV Grid Control, the row number and column namewhere the user double-clicked should display in a message of type ‘I’.
1. Define a local class LCL_EVENT_HANDLER and in this class, define an instance method tohandle the DOUBLE_CLICK event that the ALV Grid Control triggered.
Note:The class LCL_EVENT_HANDLER only acts as a handler and, otherwise, doesnot have any other functions.
Import parameters ES_ROW_NO and E_COLUMN into the handler method.
a) See the source code extract from the model solution or refer to the correspondingslides about double-click the ALV Grid Control.
2. Implement the handler method. Send a message of type ‘I’ to output the row number andcolumn name the user clicked.
Hint:You can use message 010 of message class BC401.
3. Instantiate the handler class, and register the event handler method.
a) See the source code extract from the model solution or refer to the correspondingslides about double-click the ALV Grid Control.
4. Activate and test your program.
a) Carry out this step in the usual manner.
REPORT sapbc401_alv_s1.
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_event_handler DEFINITION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*CLASS lcl_event_handler DEFINITION. PUBLIC SECTION.
METHODS on_double_click FOR EVENT double_click OF cl_gui_alv_grid IMPORTING es_row_no e_column.
Unit 7: ABAP Object-Oriented Examples
324 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 337/505
ENDCLASS. "lcl_event_handler DEFINITION
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -** CLASS lcl_event_handler IMPLEMENTATION*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- -*
CLASS lcl_event_handler IMPLEMENTATION. METHOD on_double_click.
MESSAGE i010(bc401) WITH es_row_no-row_id e_column-fieldname.
ENDMETHOD. "handler_methodENDCLASS. "lcl_event_handler IMPLEMENTATION
************** Types and Data Definitions ************************
TYPES: ty_spfli TYPE STANDARD TABLE OF spfli WITH NON-UNIQUE KEY carrid connid.
DATA: ok_code TYPE sy-ucomm.DATA: go_handler TYPE REF TO lcl_event_handler, go_container TYPE REF TO cl_gui_custom_container, go_alv_grid TYPE REF TO cl_gui_alv_grid.
DATA: gt_spfli TYPE ty_spfli.
START-OF-SELECTION.********************
SELECT * FROM spfli INTO TABLE gt_spfli.
CALL SCREEN '0100'.
*&---------------------------------------------------------------------**& Module STATUS_0100 OUTPUT*&---------------------------------------------------------------------*MODULE status_0100 OUTPUT. SET PF-STATUS 'DYNPROSTATUS'. SET TITLEBAR 'TITLE1'.ENDMODULE. " STATUS_0100 OUTPUT*&---------------------------------------------------------------------**& Module ALV_GRID OUTPUT*&---------------------------------------------------------------------
*MODULE alv_grid OUTPUT.
*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data! IF go_container IS NOT BOUND. CREATE OBJECT go_container EXPORTING container_name = 'CONTAINER_1' EXCEPTIONS others = 6. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.*** create object of class cl_gui_alv_grid to visualize data !
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 325
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 338/505
CREATE OBJECT go_alv_grid EXPORTING i_parent = go_container EXCEPTIONS others = 5. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
*** create handler instance and register handler method *******
CREATE OBJECT go_handler. SET HANDLER go_handler->on_double_click FOR go_alv_grid.
*** Call method to visualize data of internal table ************ CALL METHOD go_alv_grid->set_table_for_first_display EXPORTING i_structure_name = 'SPFLI' CHANGING it_outtab = gt_spfli
EXCEPTIONS OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
ENDIF.
ENDMODULE. " ALV_GRID OUTPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0100 INPUT*&---------------------------------------------------------------------
*MODULE user_command_0100 INPUT.
CASE ok_code. WHEN 'BACK'. SET SCREEN 0. WHEN 'EXIT'. LEAVE PROGRAM. ENDCASE.
ENDMODULE. " USER_COMMAND_0100 INPUT
Unit 7: ABAP Object-Oriented Examples
326 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 339/505
Unit 7Exercise 20
307Implement a Popup with the ALV Grid Control
Business Example
The user wants to see a list of flight connections in an ALV Grid Control. When you double-click one connection the list of flights for this connection should be displayed in a second ALVGrid Control.
Template:
SAPBC401_ALV_S1
Solution:
SAPBC401_ALV_S2
Task 1
Further, develop the solution of the previous exercise. Use advanced ALV Grid programming.First, read from the SFLIGHT database table about the flights that belong to the flightconnection the user has double-clicked.
1. Complete your program ZBC401_##_ALV (where ## is your two-digit group number), orcopy the model solution of the previous exercise.
2. In the event handler method, remove the MESSAGE statement. Define a local structure(suggested name: LS_SPFLI) to serve as a work area for internal table GT_SPFLI. FromGT_SPFLI, read the one entry that corresponds to the grid row the user double-clicked.
Hint:Use READ TABLE with an index access.
3. Is it still okay to define GT_SPFLI after the definition of the event handler class?
4. In the definition of the event handler class, define a private instance attributeMT_SFLIGHT, which is an internal (standard) table with line type SFLIGHT.
Hint:We suggest that you define a private table type TY_SFLIGHT in the sameclass.
© Copyright . All rights reserved. 327
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 340/505
5. In the event handler method, implement an array fetch for database table SFLIGHT to fillMT_SFLIGHT with those flights that have the same key fields as the flight connection theuser has clicked.
6. Activate your program, and analyze it in the ABAP Debugger . Make sure MT_SFLIGHT isfilled correctly.
Task 2
Further extend your event handler method so that the selected flights are presented in asecond ALV Grid Control which is displayed in a dialog box.
1. In your event handler class, define two reference variables as private instance attributes(suggested names: MO_CONT_POPUP and MO_ALV_POPUP). Type them with the globalclasses CL_GUI_DIALOGBOX_CONTAINER and CL_GUI_ALV_GRID.
2. In your event handler method, use these reference variables to create instances of the twoclasses.
Pay particular attention to the fact that the CREATE OBJECT is not called repeatedly whenthe event handler method is executed repeatedly.
3. To display data in the ALV Grid Control, call the SET_TABLE_FOR_FIRST_DISPLAYmethod and transfer the internal table MT_SFLIGHT with the flight data and the name ofthe line type of that internal table. Make sure this method is only called if the dialog boxcontainer and the second ALV Grid Control have just been created.
4. If the dialog box container and the second ALV Grid Control already exist, do not callmethod SET_TABLE_FOR_FIRST_DISPLAY to refresh the data displayed. Call theREFRESH_TABLE_DISPLAY method instead.
Hint:You do not have to provide values for the optional parameters of this method.
5. Activate and test your program.
Note:Note that at the moment, clicking the button in the top-right corner of thewindow does not close the dialog box container. To implement that, you wouldhave to handle event CLOSE of class CL_GUI_DIALOGBOX_CONTAINER andcall method FREE of the dialog box container. Other training courses and thedocumentation of the Control Framework explain the details of this.
REPORT sapbc401_alv_s2.
TYPES: ty_spfli TYPE STANDARD TABLE OF spfli WITH NON-UNIQUE KEY carrid connid.
DATA: gt_spfli TYPE ty_spfli.
*---------------------------------------------------------------------** CLASS lcl_event_handler DEFINITION*---------------------------------------------------------------------*
Unit 7: ABAP Object-Oriented Examples
328 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 341/505
**---------------------------------------------------------------------*CLASS lcl_event_handler DEFINITION. PUBLIC SECTION.
METHODS on_double_click FOR EVENT double_click OF cl_gui_alv_grid
IMPORTING es_row_no e_column. PRIVATE SECTION.
TYPES: ty_sflight TYPE STANDARD TABLE OF sflight WITH NON-UNIQUE KEY carrid connid fldate.
DATA: mo_cont_popup TYPE REF TO cl_gui_dialogbox_container, mo_alv_popup TYPE REF TO cl_gui_alv_grid.
DATA: mt_sflight TYPE ty_sflight.
ENDCLASS. "lcl_event_handler DEFINITION
*---------------------------------------------------------------------** CLASS lcl_event_handler IMPLEMENTATION*---------------------------------------------------------------------***---------------------------------------------------------------------*CLASS lcl_event_handler IMPLEMENTATION.
METHOD on_double_click.
DATA ls_spfli TYPE spfli.
READ TABLE gt_spfli INTO ls_spfli INDEX es_row_no-row_id.
SELECT * FROM sflight INTO TABLE mt_sflight WHERE carrid = ls_spfli-carrid AND connid = ls_spfli-connid.
IF mo_cont_popup IS NOT BOUND.
CREATE OBJECT mo_cont_popup EXPORTING width = 600 height = 300 EXCEPTIONS others = 8.
IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
CREATE OBJECT mo_alv_popup EXPORTING i_parent = mo_cont_popup EXCEPTIONS others = 5. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
mo_alv_popup->set_table_for_first_display(
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 329
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 342/505
EXPORTING i_structure_name = 'SFLIGHT' CHANGING it_outtab = mt_sflight EXCEPTIONS OTHERS = 4 ).
IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
ELSE.
mo_alv_popup->refresh_table_display( EXCEPTIONS OTHERS = 2 ). IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF. ENDIF.
* MESSAGE i010(bc401) WITH es_row_no-row_id e_column-fieldname.
ENDMETHOD. "handler_methodENDCLASS. "lcl_event_handler IMPLEMENTATION
DATA: ok_code TYPE sy-ucomm.
DATA: go_handler TYPE REF TO lcl_event_handler, go_container TYPE REF TO cl_gui_custom_container, go_alv_grid TYPE REF TO cl_gui_alv_grid.
START-OF-SELECTION.********************
SELECT * FROM spfli INTO TABLE gt_spfli.
CALL SCREEN '0100'.
*&---------------------------------------------------------------------**& Module STATUS_0100 OUTPUT*&---------------------------------------------------------------------** text
*----------------------------------------------------------------------*MODULE status_0100 OUTPUT. SET PF-STATUS 'DYNPROSTATUS'. SET TITLEBAR 'TITLE1'.ENDMODULE. " STATUS_0100 OUTPUT*&---------------------------------------------------------------------**& Module ALV_GRID OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*
MODULE alv_grid OUTPUT.*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data
Unit 7: ABAP Object-Oriented Examples
33 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 343/505
! IF go_container IS NOT BOUND. CREATE OBJECT go_container EXPORTING container_name = 'CONTAINER_1' EXCEPTIONS others = 6.
IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.*** create object of class cl_gui_alv_grid to visualize data ! CREATE OBJECT go_alv_grid EXPORTING i_parent = go_container EXCEPTIONS others = 5. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
*** create handler Instance ******************************** CREATE OBJECT go_handler.
*** set handler to react on double-click ******************* SET HANDLER go_handler->on_double_click FOR go_alv_grid.
*** Call method to visualize data of internal table ************ CALL METHOD go_alv_grid->set_table_for_first_display EXPORTING i_structure_name = 'SPFLI' CHANGING it_outtab = gt_spfli EXCEPTIONS
OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
ENDIF.
ENDMODULE. " ALV_GRID OUTPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0100 INPUT*&---------------------------------------------------------------------*
MODULE user_command_0100 INPUT. CASE ok_code. WHEN 'BACK'. SET SCREEN 0. WHEN 'EXIT'. LEAVE PROGRAM. ENDCASE.
ENDMODULE. " USER_COMMAND_0100 INPUT
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 331
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 344/505
Unit 7Solution 20
312Implement a Popup with the ALV Grid Control
Business Example
The user wants to see a list of flight connections in an ALV Grid Control. When you double-click one connection the list of flights for this connection should be displayed in a second ALVGrid Control.
Template:
SAPBC401_ALV_S1
Solution:
SAPBC401_ALV_S2
Task 1
Further, develop the solution of the previous exercise. Use advanced ALV Grid programming.First, read from the SFLIGHT database table about the flights that belong to the flightconnection the user has double-clicked.
1. Complete your program ZBC401_##_ALV (where ## is your two-digit group number), orcopy the model solution of the previous exercise.
a) Carry out this step in the usual manner.
2. In the event handler method, remove the MESSAGE statement. Define a local structure(suggested name: LS_SPFLI) to serve as a work area for internal table GT_SPFLI. FromGT_SPFLI, read the one entry that corresponds to the grid row the user double-clicked.
Hint:Use READ TABLE with an index access.
a) See the source code extract from the model solution.
3. Is it still okay to define GT_SPFLI after the definition of the event handler class?
No. To be able to access the global data object GT_SPFLI from within the local classimplementation, the data statement has to be before the local class.
4. In the definition of the event handler class, define a private instance attributeMT_SFLIGHT, which is an internal (standard) table with line type SFLIGHT.
Hint:We suggest that you define a private table type TY_SFLIGHT in the sameclass.
332 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 345/505
a) See the source code extract from the model solution.
5. In the event handler method, implement an array fetch for database table SFLIGHT to fillMT_SFLIGHT with those flights that have the same key fields as the flight connection theuser has clicked.
a) See the source code extract from the model solution.
6. Activate your program, and analyze it in the ABAP Debugger . Make sure MT_SFLIGHT isfilled correctly.
a) Carry out this step in the usual manner.
Task 2
Further extend your event handler method so that the selected flights are presented in asecond ALV Grid Control which is displayed in a dialog box.
1. In your event handler class, define two reference variables as private instance attributes
(suggested names: MO_CONT_POPUP and MO_ALV_POPUP). Type them with the globalclasses CL_GUI_DIALOGBOX_CONTAINER and CL_GUI_ALV_GRID.
a) See the source code extract from the model solution.
2. In your event handler method, use these reference variables to create instances of the twoclasses.
Pay particular attention to the fact that the CREATE OBJECT is not called repeatedly whenthe event handler method is executed repeatedly.
a) See the source code extract from the model solution.
3. To display data in the ALV Grid Control, call the SET_TABLE_FOR_FIRST_DISPLAYmethod and transfer the internal table MT_SFLIGHT with the flight data and the name of
the line type of that internal table. Make sure this method is only called if the dialog boxcontainer and the second ALV Grid Control have just been created.
a) See the source code extract from the model solution.
4. If the dialog box container and the second ALV Grid Control already exist, do not callmethod SET_TABLE_FOR_FIRST_DISPLAY to refresh the data displayed. Call theREFRESH_TABLE_DISPLAY method instead.
Hint:You do not have to provide values for the optional parameters of this method.
a) See the source code extract from the model solution.
5. Activate and test your program.
Note:Note that at the moment, clicking the button in the top-right corner of thewindow does not close the dialog box container. To implement that, you wouldhave to handle event CLOSE of class CL_GUI_DIALOGBOX_CONTAINER andcall method FREE of the dialog box container. Other training courses and thedocumentation of the Control Framework explain the details of this.
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 333
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 346/505
a) Carry out this step in the usual manner.
REPORT sapbc401_alv_s2.
TYPES: ty_spfli TYPE STANDARD TABLE OF spfli WITH NON-UNIQUE KEY carrid connid.
DATA: gt_spfli TYPE ty_spfli.
*---------------------------------------------------------------------** CLASS lcl_event_handler DEFINITION*---------------------------------------------------------------------***---------------------------------------------------------------------*CLASS lcl_event_handler DEFINITION. PUBLIC SECTION.
METHODS on_double_click FOR EVENT double_click OF cl_gui_alv_grid IMPORTING es_row_no e_column.
PRIVATE SECTION.
TYPES: ty_sflight TYPE STANDARD TABLE OF sflight WITH NON-UNIQUE KEY carrid connid fldate.
DATA: mo_cont_popup TYPE REF TO cl_gui_dialogbox_container, mo_alv_popup TYPE REF TO cl_gui_alv_grid.
DATA: mt_sflight TYPE ty_sflight.
ENDCLASS. "lcl_event_handler DEFINITION
*---------------------------------------------------------------------** CLASS lcl_event_handler IMPLEMENTATION*---------------------------------------------------------------------***---------------------------------------------------------------------*CLASS lcl_event_handler IMPLEMENTATION.
METHOD on_double_click.
DATA ls_spfli TYPE spfli.
READ TABLE gt_spfli INTO ls_spfli INDEX es_row_no-row_id.
SELECT * FROM sflight INTO TABLE mt_sflight WHERE carrid = ls_spfli-carrid AND connid = ls_spfli-connid.
IF mo_cont_popup IS NOT BOUND.
CREATE OBJECT mo_cont_popup EXPORTING width = 600 height = 300 EXCEPTIONS others = 8. IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
Unit 7: ABAP Object-Oriented Examples
334 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 347/505
ENDIF.
CREATE OBJECT mo_alv_popup EXPORTING i_parent = mo_cont_popup EXCEPTIONS others = 5.
IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
mo_alv_popup->set_table_for_first_display( EXPORTING i_structure_name = 'SFLIGHT' CHANGING it_outtab = mt_sflight EXCEPTIONS OTHERS = 4 ). IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
ELSE.
mo_alv_popup->refresh_table_display( EXCEPTIONS OTHERS = 2 ). IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
ENDIF.
* MESSAGE i010(bc401) WITH es_row_no-row_id e_column-fieldname.
ENDMETHOD. "handler_methodENDCLASS. "lcl_event_handler IMPLEMENTATION
DATA: ok_code TYPE sy-ucomm.
DATA: go_handler TYPE REF TO lcl_event_handler, go_container TYPE REF TO cl_gui_custom_container, go_alv_grid TYPE REF TO cl_gui_alv_grid.
START-OF-SELECTION.********************
SELECT * FROM spfli INTO TABLE gt_spfli.
CALL SCREEN '0100'.
*&---------------------------------------------------------------------**& Module STATUS_0100 OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------
*MODULE status_0100 OUTPUT.
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 335
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 348/505
SET PF-STATUS 'DYNPROSTATUS'. SET TITLEBAR 'TITLE1'.ENDMODULE. " STATUS_0100 OUTPUT*&---------------------------------------------------------------------**& Module ALV_GRID OUTPUT*&---------------------------------------------------------------------
** text*----------------------------------------------------------------------*MODULE alv_grid OUTPUT.*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data! IF go_container IS NOT BOUND. CREATE OBJECT go_container EXPORTING container_name = 'CONTAINER_1' EXCEPTIONS others = 6. IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.*** create object of class cl_gui_alv_grid to visualize data ! CREATE OBJECT go_alv_grid EXPORTING i_parent = go_container EXCEPTIONS others = 5. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
*** create handler Instance ******************************** CREATE OBJECT go_handler.
*** set handler to react on double-click ******************* SET HANDLER go_handler->on_double_click FOR go_alv_grid.
*** Call method to visualize data of internal table ************ CALL METHOD go_alv_grid->set_table_for_first_display EXPORTING i_structure_name = 'SPFLI' CHANGING it_outtab = gt_spfli EXCEPTIONS OTHERS = 4.
IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
ENDIF.
ENDMODULE. " ALV_GRID OUTPUT*&---------------------------------------------------------------------**& Module USER_COMMAND_0100 INPUT*&---------------------------------------------------------------------*MODULE user_command_0100 INPUT.
CASE ok_code.
Unit 7: ABAP Object-Oriented Examples
336 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 349/505
WHEN 'BACK'. SET SCREEN 0. WHEN 'EXIT'. LEAVE PROGRAM. ENDCASE.
ENDMODULE. " USER_COMMAND_0100 INPUT
Lesson: Implementing ABAP List Viewer
© Copyright . All rights reserved. 337
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 350/505
LESSON SUMMARYYou should now be able to:
● Implement simple ABAP list viewer
● Implement double-click on ABAP list viewer
Unit 7: ABAP Object-Oriented Examples
338 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 351/505
Unit 7Lesson 2
319Describing Business Add-Ins
LESSON OVERVIEWThis lesson shows you how to describe Business Add-Ins.
Business Example
As an ABAP developer, enhance functionality in an SAP standard program without altering theoriginal program.
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Describe Business Add-Ins
Business Add-In (BAdI)
Unlike Customer Exits, the BAdI of the changed software delivery process are taken intoaccount here. Generally, the typical delivery process does not only consist of providers andusers, rather several intermediate providers may be involved in the delivery chain forsoftware. So for example, you can extend a SAP application program with an industrysolution, Industrial Business Unit (IBU); the customer could then again extend the same
program.
Be flexible while working on this section:
If the participants express an interest and there is sufficient time available, you can provide adetailed demonstration from the corresponding ABAP courses (BC425 and BC427). You canbase the demonstration on the SAPBC401_BAD_D1 program and show this in stages. Youmust emphasize that this is an application example. This is not a complete, detailedintroduction to the enhancement techniques of SAP.
Note:As of SAP NW AS 7.0, you have to define and implement the newEnhancement Framework and a new type of BAdI. Here, we are dealing with anexample of how interfaces are used though, which is why the old, classic BAdItechnology is demonstrated. You should perhaps mention this beforehand.
Furthermore, the ratio of old to new BAdIs with R 7.0 is approximately 5:1 (incase a participant complains here).
© Copyright . All rights reserved. 339
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 352/505
Note:Always draw the participant’s attention to the specialized courses. This is onlyintended to provide a preview.
BAdI – Basics
Figure 128: BAdI – Basics
The adapter displayed here on the graphic is always the same. Both the partner and thecustomer are connected to the application using the same adapter.
With BAdI, an SAP application program provides the enhancement option through aninterface and an adapter class that implements the interface. The system can then implementthe interface by several possible users in the delivery chain. Multiple implementations are,therefore, also possible. Once a BAdI has been implemented, it can also be implemented byusers who appear further to the right in the chain. Furthermore, an implementation itselfcould again offer a BAdI.
Unit 7: ABAP Object-Oriented Examples
34 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 353/505
Definition of a BAdI – Basics
Figure 129: Definition of a BAdI – Basics
When you define a BAdI, you must specify an interface (IF_EX_<badi>) with corresponding,formally defined methods. The adapter class that is automatically generated during theinterface definition (CL_EX_<badi>) has, among other things, the function of calling all activeimplementations of the BAdI. This does not need to be coded, but rather happens in theadapter class itself in an undefined sequence. When you have several active implementations,there is no predefined processing sequence.
To Define a BAdI
The steps to define BAdl are as follows:1. Run the transaction code SE18.
2. Enter the definition name (<badi>).
3. Choose the Create pushbutton, enter the interface name (<badi-interface>) name in thecorresponding dialog box.
Lesson: Describing Business Add-Ins
© Copyright . All rights reserved. 341
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 354/505
Call of a BAdI
Figure 130: BAdI – The Calling Program
The graphic displays the call of a BAdI.
First, a reference variable of the type Reference to the Business Add-In interface must bedefined. An object of the adapter class is instantiated by the call of the GET_INSTANCE static
method of the CL_EXITHANDLER class. GB_ADAPTER points to this instance.The interface methods of the BAdI can now be called through this object reference.
Unit 7: ABAP Object-Oriented Examples
342 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 355/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 356/505
Implement a BAdI
Figure 132: Implementation of a BAdI – SE19
If the name of the BAdI has been determined, the BAdI can be implemented after you studythe documentation on this subject. The implementation is performed through theimplementation maintenance Tools → ABAP Workbench → Business Add-Ins → Implementation . Alternatively, you could also go to the implementations by navigatingin the menu from the BAdI definition.
To implement a BAdI, a BAdI implementation name must be issued. The naming conventionhere, as usual, is Z<impl>. A dialog box then appears for selecting the corresponding BAdI.
The code to be implemented is stored in a method of an automatically generated customerclass. For this reason, the name of the implementing class must now be given in a final dialogbox. The default name from the system is comprised of Y or Z (the namespace prefix), CL_(for class), IM_ (for implementation), and <impl> (the actual name of the implementation).
After you double-click one of the BAdI methods, you can enter the code of the method. Ofcourse, you can also create auxiliary methods in the implementing class, in order to betterstructure the required code of the BAdI method.
Note:Do not forget to activate the methods or the implementation when you havefinished.
It may be worth pointing out the relevant SAP course at this point. If you want, and if timepermits, you can add in a BAdI exercise here from the corresponding course. However, it isvital that the trainer test this in advance.
Unit 7: ABAP Object-Oriented Examples
344 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 357/505
To Implement a BAdI
The steps to implement a BAdl are as follows:
1. Run the transaction code SE19 .
2. Enter an implementation name starting in the customer name space (Z<impl>).
3. Choose the Create pushbutton, enter the BAdI name in the corresponding dialog box.
4. Choose the Continue pushbutton, enter the name of the implementing class name(proposed by the system itself).
5. Double-click the corresponding method name to implement the method code.
LESSON SUMMARYYou should now be able to:
● Describe Business Add-Ins
Lesson: Describing Business Add-Ins
© Copyright . All rights reserved. 345
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 358/505
Unit 7: ABAP Object-Oriented Examples
346 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 359/505
Unit 7
325Learning Assessment
1. The ALV Grid Control is a tool that you can use to display nonhierarchical lists in astandardized form.
Determine whether this statement is true or false.
X True
X False
2. Container controls do not provide the technical connection between the screen andapplication control.
Determine whether this statement is true or false.
X True
X False
3. To create a handler object for an event, we have to first define a ____________.
Choose the correct answer.
X A class
X B structure
X C method
X D attribute
4. A handler method can be either a class method (static method) or an instance method ofan object.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 347
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 360/505
5. With a BAdI, an SAP application program provides the enhancement option through aninterface.
Determine whether this statement is true or false.
X True
X False
6. An object of the adapter class is instantiated by the call of the GET_INSTANCE staticmethod of the CL_EXITHANDLER class.
Determine whether this statement is true or false.
X True
X False
7. To implement a BAdI, a BAdI implementation name must be issued.
Determine whether this statement is true or false.
X True
X False
8. The code to be implemented is stored in a __________ of an automatically generatedcustomer class.
Choose the correct answer.
X A method
X B structure
X C object
Unit 7: Learning Assessment
348 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 361/505
Unit 7
327Learning Assessment- Answers
1. The ALV Grid Control is a tool that you can use to display nonhierarchical lists in astandardized form.
Determine whether this statement is true or false.
X True
X False
2. Container controls do not provide the technical connection between the screen andapplication control.
Determine whether this statement is true or false.
X True
X False
3. To create a handler object for an event, we have to first define a ____________.
Choose the correct answer.
X A class
X B structure
X C method
X D attribute
4. A handler method can be either a class method (static method) or an instance method ofan object.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 349
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 362/505
5. With a BAdI, an SAP application program provides the enhancement option through aninterface.
Determine whether this statement is true or false.
X True
X False
6. An object of the adapter class is instantiated by the call of the GET_INSTANCE staticmethod of the CL_EXITHANDLER class.
Determine whether this statement is true or false.
X True
X False
7. To implement a BAdI, a BAdI implementation name must be issued.
Determine whether this statement is true or false.
X True
X False
8. The code to be implemented is stored in a __________ of an automatically generatedcustomer class.
Choose the correct answer.
X A method
X B structure
X C object
Unit 7: Learning Assessment- Answers
35 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 363/505
UNIT 8 Object-Oriented DesignPatterns
Lesson 1
Implementing Special Object-Oriented Techniques 353
Lesson 2
Implementing the Singleton Pattern 361Exercise 21: Implement the Singleton Pattern 365
Lesson 3
Implementing Factory Classes Using Friendship 376Exercise 22: Implement a Factory Class Using Friendship 379
Lesson 4
Implementing Persistent Objects 386
UNIT OBJECTIVES
● Implement abstract classes
● Implement final classes
● Access internal tables with object references
● Call navigation methods
● Define the visibility of the instance constructor
● Implement factory methods
● Implement the singleton pattern
● Implement friendship relationships
● Explain persistence services
● Examine persistent classes
● Create persistent objects
● Read persistent objects
© Copyright . All rights reserved. 351
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 364/505
● Create OO transactions
Unit 8: Object-Oriented Design Patterns
352 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 365/505
Unit 8Lesson 1
331Implementing Special Object-Oriented
Techniques
LESSON OVERVIEWThis lesson shows you how to implement abstract classes and final classes, access internaltables with object references, and call the navigation methods.
Business Example
You want to add special object-oriented programming techniques to your ABAP Objectsimplementations. For this reason, you require the following knowledge:
● Define abstract classes.
● Define abstract methods.
● Define final classes.
● Define final methods.
● Understand the special use of public read-only attributes.
● Understand the term “navigational method”.
● Chain functional methods.
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement abstract classes
● Implement final classes
● Access internal tables with object references
● Call navigation methods
● Define the visibility of the instance constructor
© Copyright . All rights reserved. 353
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 366/505
Abstract Classes
Figure 133: Abstract Classes and Abstract Methods
You can prevent the instantiation of a class by using the abstract addition with the classstatement. Super classes are a typical use for abstract classes, as they are not intended to beinstantiated themselves, but their subclasses are.
In such an abstract class, you can define abstract methods (among other things). This meansthat you can leave their implementation open. If the subclass of that class is not abstract, theabstract methods must be redefined there. This means that it must be implemented for thefirst time.
Note:The relevant indicator is in the Class Builder on the Attributes tab for that class ormethod.
In this particular case, we suggest that you do not conduct a system demonstration at thispoint.
References to such abstract classes can, therefore, be used for polymorphic access tosubclass instances. Static methods cannot be abstract because they cannot be redefined.
Unit 8: Object-Oriented Design Patterns
354 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 367/505
Final Classes
Figure 134: Final Classes and Methods
You can prevent a class from being inherited by using the final addition with the classstatement. You can prevent a method from being redefined by using the final addition with themethods statement.
Note:The relevant indicator is in the Class Builder on the Attributes tab for that class ormethod.
In this particular case, we suggest that you do not conduct a system demonstration at thispoint.
Thus, all methods of a final class are implicitly final. Therefore, you may not repeat the FINALaddition in the methods themselves. Classes that are abstract and final should only containstatic components.
Lesson: Implementing Special Object-Oriented Techniques
© Copyright . All rights reserved. 355
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 368/505
Internal Tables with Object References
Figure 135: Read Access to a Table with Object References
We have learned in a previous section that you cannot store object references in internaltables. This is used, in particular, to implement associations. However, we have not yetdiscussed how we should retrieve a specific object from such a list. The above figure gives anexample of how this could be achieved. The object reference is stored in the table along withsome key information. In the example, it is make and model of the vehicle. The object
reference can easily be retrieved through this key information. Unfortunately, this techniqueimplies a redundant storage of information. The key values are already stored in attributes ofthe object.
Unit 8: Object-Oriented Design Patterns
356 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 369/505
Read Access Using Public Attributes
Figure 136: Read Access Using Public Attributes
By making the key attributes public, this redundancy can be avoided, as shown in the figure.As we can see, public attributes may be used directly in the statements with which we accessinternal tables. For example, READ TABLE ... and LOOP AT ..... The expression TABLE_LINE,used here, is a built-in part of the ABAP language. We have to use TABLE_LINE whenever an
internal table’s line type is not a structure type but an elementary data type. Such internaltables have just one column, which does not have a column name. TABLE_LINE is used as thegeneric column name for this single column.
Hint:It is against the fundamental principles of object-oriented programming to makeattributes public. Unfortunately, ABAP does not allow you to use functionalmethods like GET_MAKE, GET_MODEL, and so on that is located on the left-handside of WHERE clauses and WITH KEY additions. Therefore, the use of publicattributes should be tolerable in such special cases – but they must remain read-only.
Demonstration: How to Implement Access to Internal Tables with Object References
Use programs SAPBC401_SPC_AGGREGATION_D1 andSAPBC401_SPC_AGGREGATION_D2 to demonstrate this. ProgramSAPBC401_SPC_AGGREGATION_D3 shows how complicated it would be to use neitherpublic attributes nor store the key values outside the object. Showing this demo is optional.
Lesson: Implementing Special Object-Oriented Techniques
© Copyright . All rights reserved. 357
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 370/505
Call and Chain Navigation Methods
Figure 137: Navigation Methods and Chaining of Method Calls
We have learned that associations like aggregations and compositions are an importantdesign principle of object-oriented programming. An association means that at runtime, aninstance of one class stores references to objects of another class.
Classes that have other classes associated with them often come with methods that returnone of the stored references to the caller. Such methods are often called navigation methods,as they can be used to navigate from one object to another. In the following example, theLCL_VEHICLE class is associated with the LCL_RENTAL class. Class LCL_RENTAL providesthe navigation method GET_VEHICLE.
Often, the purpose of navigating from one object to another is to call a single method of thisother object. Before the Release of SAP NetWeaver 7.0 EhP2, it was mandatory to first storethe reference to the new object in a reference variable. As of SAP NetWeaver 7.0 EhP2, wecan chain method calls, that is, we can directly call a method of the object that the navigationmethod returns.
Hint:This technique is not restricted to the chaining of two methods. In morecomplicated object models, it is possible to chain any number of methods.
Demonstration: How to Call and Chain Navigation Methods
Examples of navigation methods are already part of the how to implement access to internaltables with object references demonstration programs(SAPBC401_SPC_AGGREGATION_D1, SAPBC401_SPC_AGGREGATION_D2, andSAPBC401_SPC_AGGREGATION_D3). Copy one of those programs and replace the two
Unit 8: Object-Oriented Design Patterns
358 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 371/505
method calls by a method chain. Alternatively, analyze the main programSAPBC401_SPC_METHOD_CHAIN_D1. Program SAPBC401_SPC_METHOD_CHAIN_D2demonstrates that with SAP NW 7.0 EhP2, it is also possible to use functional methods asactual parameters for importing the parameters of methods. Showing this program isoptional.
Visibility of the Instance Constructor
Figure 138: Implicit Setting of the Instance Constructor’s Visibility
In ABAP Objects, we can restrict the visibility of the instance constructor. If we have restrictedthe visibility of the instance constructor, the create object statements to instantiate this classare only allowed in certain parts of the coding.
There are three types of instance constructor’s, as follows:● PRIVATE
If a class has a private instance constructor, we can only instantiate it from within the classitself, typically in static methods that are defined for that purpose. These methods aresometimes called “Factor-Methods”.
● PROTECTED
If the instance constructor is protected, the visibility is extended to all of its subclasses,that is, the subclasses can also create instances of the class.
● PUBLIC
A public instance constructor is the default: Instances of the class can be createdanywhere – inside the class itself, inside other classes, or even in a non-object-orientedpart of the program (for example the main program). We set the visibility by using thecreate addition with the class statement.
Lesson: Implementing Special Object-Oriented Techniques
© Copyright . All rights reserved. 359
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 372/505
Note:The relevant indicator is in the Class Builder on the Attributes tab for the relevantclass.
Hint:The visibility of the constructor is not set by placing the definition of the methodconstructor in the respective section of the class definition. In fact, before SAPNetWeaver 7.0, it was mandatory to place the constructor syntactically in thepublic section. Since SAP NetWeaver 7.0, it is allowed but not required to placethe constructor in the protected or private section – if this is not more restrictivethan the create... addition in the class definition. This is to increase thereadability of the coding.
Demonstration: How to Restrict the Visibility of the Instance Constructor
First, demonstrate how to restrict the instantiation of a class especially for global classes.Then, explain or even demonstrate the effect of such a restriction. Then, make clear to theparticipants that such a restriction is only sensible when implementing the instantiation ofthe class within the class or its subclasses. This should lead you naturally to the factorymethod.
LESSON SUMMARYYou should now be able to:
● Implement abstract classes
● Implement final classes
● Access internal tables with object references
● Call navigation methods
● Define the visibility of the instance constructor
Unit 8: Object-Oriented Design Patterns
36 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 373/505
Unit 8Lesson 2
339Implementing the Singleton Pattern
LESSON OVERVIEWThis lesson explains the concepts of factory methods, singleton pattern, and theirimplementation.
Business Example:
You want to add special object-oriented programming techniques to your ABAP Objectsimplementations. For this reason, you require the following knowledge:
● An understanding of factory method
● An understanding of singleton pattern
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement factory methods
● Implement the singleton pattern
Factory Methods
Restricting the visibility of the instance constructor only makes sense if instantiation is donesomewhere within the class or its subclasses, in case of CREATE PROTECTED. Often suchclasses provide a public static method that creates an instance of this class and returns thereference to this instance to the caller. Such methods are sometimes called “factorymethods”. Like the instance constructor itself, factory methods are executed when aninstance of the class is created. However, they have some advantages.
Some advantages of factory methods are as follows:● A factory method can have coding that executes before the actual instantiation.
For example, the method can do checks, read data from the database, or set locks, beforeactually creating the instance. If an error occurs during this, no instance is created; andtherefore, no memory is allocated for it.
● A class can have more than one factory method. Each of them could have a differentimplementation and signature.
This makes it possible to create instances of the same class based on differentinformation. As an example, one factory method could create a new instance, offeringinput parameters for all attributes, while another factory method would only import keyinformation and then retrieve the other attribute values from the database.
● Factory methods can be used to administrate the instances of a class within the classitself.
© Copyright . All rights reserved. 361
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 374/505
This is often used to avoid the creation of many, identical instances. A reference of everynew instance is stored in a private static attribute of the class (an internal table). Wheneverthe factory method is called, it first checks whether an instance with this key alreadyexists. If so, it returns the existing instance instead of creating a new one.
● A factory method can be used to instantiate one of the subclasses rather than the class
itself. As an example, the factory method of an airplane class could first check the planetype, then instantiate either a cargo or a passenger plane.
Example for a Class with Factory Method
Figure 139: Example for a Class with Factory Method
The example illustrates a class that keeps a reference to all its instances in a static attribute.The instantiation is restricted to the class itself and is only done in static method FACTORY.When the method is called, it first checks whether an identical instance has already beencreated. If so, it returns the existing instance instead of creating a new one.
Hint:It could be worth mentioning that in this example, it is not necessary to make
attributes public for the READ TABLE statement. As the factory method lieswithin the class, it has full access to all private attributes.
Demonstration: How to Implement a Factory Method
You could either do your own demonstration or use program SAPBC401_SPC_FACTORY_D1to illustrate the factory principle. Make sure you explain the advantages compared to theconstructor.
Unit 8: Object-Oriented Design Patterns
362 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 375/505
The Singleton Pattern
Figure 140: Singleton Class – Using a Factory Method
In many cases, you need to prevent a class from being instantiated more than once for thesame program context. You can do this using the singleton concept.
There are various different ways to implement a singleton class. The first singleton pattern is
a special case of the factory concept. Instead of storing several instances, the class storesonly one instance. When the factory method GET_INSTANCE is called for the first time, itinstantiates the class. For every subsequent call, it simply returns the reference to theexisting object.
Lesson: Implementing the Singleton Pattern
© Copyright . All rights reserved. 363
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 376/505
Singleton Class 2 – Using the Static Constructor
Figure 141: Singleton Class 2 – Using the Static Constructor
The class uses its static constructor to create the single instance in advance. TheGET_INSTANCE method no longer creates the instance but only returns a reference to thealready existing instance.
Hint:In a third variant of the singleton pattern, the GO_INSTANCE static attribute ismade public and read-only. The GET_INSTANCE method is no longer needed.
Demonstration: How to Implement the Singleton Pattern
Be sure to demonstrate this concept in the system because it is a basic programmingpattern for all standard object-oriented programming languages. ProgramsSAPBC401_SPC_SINGLETON_D1 and SAPBC401_SPC_SINGLETON_D2 correspond to thetwo patterns shown in the graphics. Program SAPBC401_SPC_SINGLETON_D3 gives an
example of a singleton class where the object reference is stored in a public read-onlyattribute.
Unit 8: Object-Oriented Design Patterns
364 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 377/505
Unit 8Exercise 21
343Implement the Singleton Pattern
Business Example
You want to improve the robustness of your application. You want to make sure of thefollowing:
● That the two special kinds of airplanes (passenger and cargo) are not further specialized
● That only specific airplanes are created
●
That the travel agency can only be instantiated onceTemplate:
SAPBC401_GCL_S2
Solution:
SAPBC401_SPC_S1
Task 1
Use the techniques of ABAP Objects to avoid the further specialization of passenger andcargo planes.
1. Complete your ZBC401_##_MAIN program or copy the template program.
2. Declare classes LCL_PASSENGER_PLANE and LCL_CARGO_PLANE as final.
3. What would happen if you declared class LCL_AIRPLANE final? (Try it out if you are notsure)
4. What would happen if you only made method DISPLAY_ATTRIBUTES in classLCL_AIRPLANE final? (Try it out if you are not sure)
Task 2
Use the techniques of ABAP Objects to inhibit the instantiation of class LCL_AIRPLANE.
1. Declare LCL_AIRPLANE as an abstract class.
© Copyright . All rights reserved. 365
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 378/505
2. Proof that it is no longer allowed to instantiate the class itself. In your main program,declare a reference variable TYPE REF TO lcl_airplane and implement a CREATE OBJECTstatement for it. After the syntax, check remove the CREATE OBJECT statement.
Task 3
Make sure the LCL_TRAVEL_AGENCY class can only be instantiated once in your program.Implement one of the singleton patterns discussed in the course.
1. Restrict the visibility of the instance constructor and inhibit any inheritance from the class.
2. Define a static attribute to store a reference to the one instance there. Depending on thepattern you implement, make it private or public and read-only.
3. Depending on the pattern you implement, define and implement a static constructorand/or a GET_INSTANCE method. Implement the instantiation of the class according tothe singleton pattern.
4. Adjust the main program. Remove the CREATE OBJECT statement for the travel agencyfrom the main program. Depending on the single pattern you implemented, replace it witha call of the GET_INSTANCE method or with an access to the public attribute.
5. Optional: If you have implemented a pattern that includes a GET_INSTANCE method, usea method chain to retrieve the singleton instance and call its DISPLAY_ATTRIBUTEmethod in one statement.
Include BC401_SPC_S1_CARRIER
*------------------------------------------------------------------** CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*CLASS lcl_airplane DEFINITION
ABSTRACT . ... ENDCLASS. "lcl_airplaneDEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION*---------------------------------------------------------------------
* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane
FINAL. ... ENDCLASS. "lcl_cargo_planeDEFINITION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_planeIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane
Unit 8: Object-Oriented Design Patterns
366 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 379/505
FINAL. ... ENDCLASS. "lcl_passenger_planeDEFINITION*---------------------------------------------------------------------
* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION
Include BC401_SPC_S1_AGENCY
*---------------------------------------------------------------------* * CLASS lcl_travel_agency DEFINITION*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION
FINAL CREATE PRIVATE . PUBLIC SECTION.
CLASS-METHODS: get_instance RETURNING value(ro_instance) TYPE REF TO lcl_travel_agency. METHODS: display_agency_partners, display_attributes. PRIVATESECTION. DATA: mv_name TYPE string, mt_partners TYPE TABLE OF REF TOif_partner.
CLASS-DATA: go_instance TYPE REF TO lcl_travel_agency.
METHODS: constructor IMPORTING iv_name TYPE string. METHODS: on_partner_created FOR EVENT partner_created OF if_partnerIMPORTING sender. ENDCLASS. "lcl_travel_agency DEFINITION*---------------------------------------------------------------------* * CLASS lcl_travel_agency IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION.
METHOD get_instance.
IF go_instance IS NOT BOUND.
Lesson: Implementing the Singleton Pattern
© Copyright . All rights reserved. 367
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 380/505
CREATE OBJECT go_instance EXPORTING iv_name = 'Travel&Smile Travel'. ENDIF.
ro_instance = go_instance.
ENDMETHOD. "get_instance METHOD display_attributes. WRITE: / icon_private_files AS ICON,'Travel Agency:'(007), mv_name. SKIP. display_agency_partners( ).ENDMETHOD. "display_attributes METHOD display_agency_partners. DATA:lo_partner TYPE REF TO if_partner. WRITE 'Here are the partners of thetravel agency:'(008). ULINE. LOOP AT mt_partners INTO lo_partner.lo_partner->display_partner( ). ENDLOOP. ENDMETHOD."display_agency_partners METHOD constructor. mv_name = iv_name. SETHANDLER on_partner_created FOR ALL INSTANCES. ENDMETHOD. "constructorMETHOD on_partner_created. APPEND sender TO mt_partners. ENDMETHOD."on_partner_created ENDCLASS.
Main Program SAPBC401_SPC_S1
REPORT sapbc401_spc_s1. TYPE-POOLS icon. INCLUDE bc401_spc_s1_agency.INCLUDE bc401_spc_s1_carrier. INCLUDE bc401_spc_s1_rental. DATA:go_hotel TYPE REF TO cl_hotel2, go_agency TYPE REF TOlcl_travel_agency, go_vehicle TYPE REF TO lcl_vehicle, go_truck TYPEREF TO lcl_truck, go_bus TYPE REF TO lcl_bus, go_rental TYPE REF TOlcl_rental, go_passenger TYPE REF TO lcl_passenger_plane, go_cargoTYPE REF TO lcl_cargo_plane, go_carrier TYPE REF TO lcl_carrier. START-OF-SELECTION. ******************* ******* create travel_agency**********************************
* CREATE OBJECT go_agency* EXPORTING* iv_name = 'Travel&Smile Travel'.
go_agency = lcl_travel_agency=>get_instance( ). ******* create hotel ******************************************CREATE OBJECT go_hotel EXPORTING iv_name = 'Sleep Well Hotel' iv_beds= 345. ******* create rental *****************************************CREATE OBJECT go_rental EXPORTING iv_name = 'Happy Car Rental'.******* create truck ****************************************** CREATEOBJECT go_truck EXPORTING iv_make = 'MAN' iv_cargo = 45. *******create truck ****************************************** CREATE OBJECTgo_bus EXPORTING iv_make = 'Mercedes' iv_passengers = 80. *******create truck ****************************************** CREATE OBJECTgo_truck EXPORTING iv_make = 'VOLVO' iv_cargo = 48. ***** CreateCarrier ****************************************** CREATE OBJECTgo_carrier EXPORTING iv_name = 'Smile&Fly Travel'. ***** PassengerPlane ***************************************** CREATE OBJECTgo_passenger EXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400'iv_seats = 345 EXCEPTIONS wrong_planetype = 1. IF sy-subrc <> 0.WRITE: / icon_failure AS ICON, 'Wrong plane type'. ENDIF. ***** cargoPlane ********************************************* CREATE OBJECTgo_cargo EXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F'iv_cargo = 533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc <> 0.WRITE: / icon_failure AS ICON, 'Wrong plane type'. ENDIF. ******* showattributes of all partners of travel_agency ****** go_agency-
Unit 8: Object-Oriented Design Patterns
368 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 381/505
>display_attributes( ).
* Optional part: Use method chain:*- - - - - - - - - - - - - -–- - - - - - - - - - - - - - - - - -** lcl_travel_agency=>get_instance( )->display_attributes( ).
Lesson: Implementing the Singleton Pattern
© Copyright . All rights reserved. 369
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 382/505
Unit 8Solution 21
348Implement the Singleton Pattern
Business Example
You want to improve the robustness of your application. You want to make sure of thefollowing:
● That the two special kinds of airplanes (passenger and cargo) are not further specialized
● That only specific airplanes are created
●
That the travel agency can only be instantiated onceTemplate:
SAPBC401_GCL_S2
Solution:
SAPBC401_SPC_S1
Task 1
Use the techniques of ABAP Objects to avoid the further specialization of passenger andcargo planes.
1. Complete your ZBC401_##_MAIN program or copy the template program.a) Carry out this step in the usual manner. Additional information is available in the SAP
Library.
2. Declare classes LCL_PASSENGER_PLANE and LCL_CARGO_PLANE as final.
a) See the source code extract from the model solution.
3. What would happen if you declared class LCL_AIRPLANE final? (Try it out if you are notsure)
This would result in a syntax error as classes LCL_CARGO_PLANE and
LCL_PASSENGER_PLANE already inherit from this class.
4. What would happen if you only made method DISPLAY_ATTRIBUTES in classLCL_AIRPLANE final? (Try it out if you are not sure)
This would result in a syntax error as the method is already redefined in classesLCL_CARGO_PLANE and LCL_PASSENGER_PLANE.
Task 2
Use the techniques of ABAP Objects to inhibit the instantiation of class LCL_AIRPLANE.
37 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 383/505
1. Declare LCL_AIRPLANE as an abstract class.
a) See the source code extract from the model solution.
2. Proof that it is no longer allowed to instantiate the class itself. In your main program,declare a reference variable TYPE REF TO lcl_airplane and implement a CREATE OBJECTstatement for it. After the syntax, check remove the CREATE OBJECT statement.
a) Carry out this step in the usual manner.
Task 3
Make sure the LCL_TRAVEL_AGENCY class can only be instantiated once in your program.Implement one of the singleton patterns discussed in the course.
1. Restrict the visibility of the instance constructor and inhibit any inheritance from the class.
a) Use the FINAL and CREATE PRIVATE additions to the CLASS ... DEFINITIONstatement. Optionally, move the definition of the instance constructor to the privatesection. See the source code extract from the model solution.
2. Define a static attribute to store a reference to the one instance there. Depending on thepattern you implement, make it private or public and read-only.
a) See the source code extract from the model solution.
3. Depending on the pattern you implement, define and implement a static constructorand/or a GET_INSTANCE method. Implement the instantiation of the class according tothe singleton pattern.
a) See the source code extract from the model solution.
4. Adjust the main program. Remove the CREATE OBJECT statement for the travel agencyfrom the main program. Depending on the single pattern you implemented, replace it with
a call of the GET_INSTANCE method or with an access to the public attribute.a) See the source code extract from the model solution.
5. Optional: If you have implemented a pattern that includes a GET_INSTANCE method, usea method chain to retrieve the singleton instance and call its DISPLAY_ATTRIBUTEmethod in one statement.
a) See the source code extract from the model solution.
Include BC401_SPC_S1_CARRIER
*------------------------------------------------------------------** CLASS lcl_airplane DEFINITION **------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION
ABSTRACT . ... ENDCLASS. "lcl_airplaneDEFINITION*------------------------------------------------------------------* *CLASS lcl_airplane IMPLEMENTATION **------------------------------------------------------------------*CLASS lcl_airplane IMPLEMENTATION. ... ENDCLASS. "lcl_airplaneIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane
Lesson: Implementing the Singleton Pattern
© Copyright . All rights reserved. 371
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 384/505
FINAL. ... ENDCLASS. "lcl_cargo_planeDEFINITION*---------------------------------------------------------------------
* * CLASS lcl_cargo_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. ... ENDCLASS. "lcl_cargo_planeIMPLEMENTATION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane
FINAL. ... ENDCLASS. "lcl_passenger_planeDEFINITION*---------------------------------------------------------------------* * CLASS lcl_passenger_plane IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. ... ENDCLASS."lcl_passenger_plane IMPLEMENTATION
Include BC401_SPC_S1_AGENCY
*---------------------------------------------------------------------* * CLASS lcl_travel_agency DEFINITION*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION
FINAL CREATE PRIVATE . PUBLIC SECTION.
CLASS-METHODS: get_instance RETURNING value(ro_instance) TYPE REF TO lcl_travel_agency. METHODS: display_agency_partners, display_attributes. PRIVATESECTION. DATA: mv_name TYPE string, mt_partners TYPE TABLE OF REF TOif_partner.
CLASS-DATA: go_instance TYPE REF TO lcl_travel_agency.
METHODS: constructor IMPORTING
Unit 8: Object-Oriented Design Patterns
372 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 385/505
iv_name TYPE string. METHODS: on_partner_created FOR EVENT partner_created OF if_partnerIMPORTING sender. ENDCLASS. "lcl_travel_agency DEFINITION*---------------------------------------------------------------------* * CLASS lcl_travel_agency IMPLEMENTATION*---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION.
METHOD get_instance.
IF go_instance IS NOT BOUND. CREATE OBJECT go_instance EXPORTING iv_name = 'Travel&Smile Travel'. ENDIF.
ro_instance = go_instance.
ENDMETHOD. "get_instance METHOD display_attributes. WRITE: / icon_private_files AS ICON,'Travel Agency:'(007), mv_name. SKIP. display_agency_partners( ).ENDMETHOD. "display_attributes METHOD display_agency_partners. DATA:lo_partner TYPE REF TO if_partner. WRITE 'Here are the partners of thetravel agency:'(008). ULINE. LOOP AT mt_partners INTO lo_partner.lo_partner->display_partner( ). ENDLOOP. ENDMETHOD."display_agency_partners METHOD constructor. mv_name = iv_name. SETHANDLER on_partner_created FOR ALL INSTANCES. ENDMETHOD. "constructorMETHOD on_partner_created. APPEND sender TO mt_partners. ENDMETHOD."on_partner_created ENDCLASS.
Main Program SAPBC401_SPC_S1
REPORT sapbc401_spc_s1. TYPE-POOLS icon. INCLUDE bc401_spc_s1_agency.INCLUDE bc401_spc_s1_carrier. INCLUDE bc401_spc_s1_rental. DATA:go_hotel TYPE REF TO cl_hotel2, go_agency TYPE REF TOlcl_travel_agency, go_vehicle TYPE REF TO lcl_vehicle, go_truck TYPEREF TO lcl_truck, go_bus TYPE REF TO lcl_bus, go_rental TYPE REF TOlcl_rental, go_passenger TYPE REF TO lcl_passenger_plane, go_cargoTYPE REF TO lcl_cargo_plane, go_carrier TYPE REF TO lcl_carrier. START-OF-SELECTION. ******************* ******* create travel_agency**********************************
* CREATE OBJECT go_agency* EXPORTING* iv_name = 'Travel&Smile Travel'.
go_agency = lcl_travel_agency=>get_instance( ). ******* create hotel ******************************************CREATE OBJECT go_hotel EXPORTING iv_name = 'Sleep Well Hotel' iv_beds= 345. ******* create rental *****************************************CREATE OBJECT go_rental EXPORTING iv_name = 'Happy Car Rental'.******* create truck ****************************************** CREATEOBJECT go_truck EXPORTING iv_make = 'MAN' iv_cargo = 45. *******
Lesson: Implementing the Singleton Pattern
© Copyright . All rights reserved. 373
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 386/505
create truck ****************************************** CREATE OBJECTgo_bus EXPORTING iv_make = 'Mercedes' iv_passengers = 80. *******create truck ****************************************** CREATE OBJECTgo_truck EXPORTING iv_make = 'VOLVO' iv_cargo = 48. ***** CreateCarrier ****************************************** CREATE OBJECTgo_carrier EXPORTING iv_name = 'Smile&Fly Travel'. ***** PassengerPlane ***************************************** CREATE OBJECT
go_passenger EXPORTING iv_name = 'LH BERLIN' iv_planetype = '747-400'iv_seats = 345 EXCEPTIONS wrong_planetype = 1. IF sy-subrc <> 0.WRITE: / icon_failure AS ICON, 'Wrong plane type'. ENDIF. ***** cargoPlane ********************************************* CREATE OBJECTgo_cargo EXPORTING iv_name = 'US Hercules' iv_planetype = '747-200F'iv_cargo = 533 EXCEPTIONS wrong_planetype = 1. IF sy-subrc <> 0.WRITE: / icon_failure AS ICON, 'Wrong plane type'. ENDIF. ******* showattributes of all partners of travel_agency ****** go_agency->display_attributes( ).
* Optional part: Use method chain:*- - - - - - - - - - - - - -–- - - - - - - - - - - - - - - - - -** lcl_travel_agency=>get_instance( )->display_attributes( ).
Unit 8: Object-Oriented Design Patterns
374 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 387/505
LESSON SUMMARYYou should now be able to:
● Implement factory methods
● Implement the singleton pattern
Lesson: Implementing the Singleton Pattern
© Copyright . All rights reserved. 375
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 388/505
Unit 8Lesson 3
354Implementing Factory Classes Using
Friendship
LESSON OVERVIEWThis lesson explains the method of implementing factory classes using friendship.
Business Example
As a developer, create classes using friendship for an airplane. For this reason, you requirethe following knowledge:
● An understanding of the definition of friendship relationships● An understanding of friendship and inheritance
● An understanding of the implementation of factory classes
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Implement friendship relationships
Definition of Friendship Relationships
Figure 142: Definition of a Friendship Relationship Between Classes
In some cases, classes have to work together so closely that one class needs access to theother’s protected and private components. Similarly, one class might need to be able tocreate instances of the other class regardless of the visibility of the constructor. To avoid
376 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 389/505
making these options available to all users of the class, you can use the concept of classfriendship. A class can grant friendship to other classes and interfaces and, hence, to allclasses that implement the interface.
This is the purpose of the FRIENDS addition of the CLASS statement or the FRIENDS tab inthe Class Builder. All classes and interfaces to which friendship is granted are listed there.
Granting friendship is one-sided.
A class granting friendship is not automatically a friend of its friends. If a class grantingfriendship wants to access the non-public components of a friend, this friend must alsoexplicitly grant friendship to it.
Implementation of Factory Classes
Figure 143: Example of a Factory Class
A typical application of the friends concept is the definition of a factory class. Like the factorymethod we discussed earlier, a factory class creates and administrates the instances of aclass. By outsourcing the administration to a dedicated class, the class itself is kept smallerand easier to understand.
In the example, class LCL_FACTORY serves as a factory class for airplanes. It provides a
public method CREATE_AIRPLANE in which it either instantiates class LCL_AIRPLANE orreturns a reference to an already existing instance. To restrict the instantiation, classLCL_AIRPLANE is defined with addition CREATE PRIVATE. By adding FRIENDSLCL_FACTORY, it allows the factory class and only the factory class to create airplaneinstances and to access the private attributes.
Lesson: Implementing Factory Classes Using Friendship
© Copyright . All rights reserved. 377
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 390/505
Hint:Another advantage of the dedicated factory class is that if the class hassubclasses, the decision on which of the classes should be instantiated could bedone inside the factory class rather than by the calling program. This will depend
on the input. For example, the plane type. In this, the CREATE_AIRPLANEmethod could create and return an instance of either LCL_CARGO_PLANE orLCL_PASSENGER_PLANE.
Friendship and Inheritance
The friend attribute is inherited. Classes that inherit from friends and interfaces, containing afriend as a component interface, also become friends. Therefore, advise that extreme cautionshould be taken when granting friendship. The higher up a friend is in the inheritance tree, themore subclasses can access all components of a class that grants friendship.
Conversely, granting friendship is not inherited. A friend of a superclass is, therefore, not
automatically a friend of its subclasses.
Demonstration: How to Implement a Factory Class Using Friendship
Friendship relations are a technique that in some respect contradicts the basic encapsulationprinciple of object-oriented programming. It, therefore, does not exist in some prominentobject-oriented programming languages like Java. Because of that, you need a very strongmotivation for using it. Outsourcing the administration of instances to a factory class couldbe such a motivation. The class itself is kept small. By granting friendship to the factory classand only to it can you restrict instantiation and direct access to the key attributes.
We suggest that you first explain the basic idea of friendship relations. Then, demonstratehow you grant friendship to another class, especially in the Class Builder. You may do a littledemonstration to show the effect of granting friendship.
Unit 8: Object-Oriented Design Patterns
378 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 391/505
Unit 8Exercise 22
357Implement a Factory Class Using Friendship
Business Example
Instead of instantiating airplane objects in the main program directly, you should createairplanes by using a factory class. The factory class should provide one single factory method.Depending on the input, the factory class decides, inside this factory method, whether tocreate a cargo plane or a passenger plane.
Template:
SAPBC401_SPC_S1Solution:
SAPBC401_ SPC_S2
Task 1
In your program, define a factory class (suggested name: LCL_AIRPLANE_FACTORY) with apublic static factory method for airplanes (suggested name: CREATE_AIRPLANE).
The factory method should have suitably typed import parameters for name, plane type,cargo, and seats. The factory method for import parameters cargo and sheet can be optional.
It should also have a single returning parameter to return a reference to an airplane instance –
either a cargo plane or a passenger plane.
1. Complete your program ZBC401_##_MAIN (where ## is your two-digit group number), orcopy the template program.
2. Edit the include, which contains the classes for airplanes. Add the definition of the newclass there.
3. Within the class, define a public static factory method for airplanes. Define four importparameters for name, plane type, cargo, and seats. Name and type them exactly as in theconstructors of your airplane classes. Make the parameters for cargo and seats optional.
Hint:Use addition OPTIONAL to do so.
4. Define a returning parameter (suggested name: RO_AIRPLANE). How do you have to typethe parameter so that the method can return a reference to either a cargo plane instanceor a passenger plane instance?
Task 2
© Copyright . All rights reserved. 379
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 392/505
Implement the factory method. Depending on the optional parameter that is supplied, createeither a cargo plane instance or a passenger plane instance. Define a suitable exception, andraise it if both optional parameters are supplied or none of them.
1. In the factory method, define two local reference variables. Type one with the class forcargo planes (LCL_CARGO_PLANE) and one with the class for passenger planes
(LCL_PASSENGER_PLANE).2. Implement an IF-structure in which you analyze the content of the import parameters for
cargo and seats. Create either an instance of the cargo plane class or the passenger planeclass. In the case of success, move the reference to the new object to the returningparameter.
3. In the definition of the factory class, add two exceptions. One that you raise if a wrongplane type was specified (suggested name: WRONG_PLANETYPE) and one that you raiseif both or none of the optional parameters were supplied (suggested name:WRONG_PARAM_COMBINATION).
Task 3
Restrict the creation of cargo planes and passenger planes, so that they can only be createdfrom inside the factory class.
1. Use the CREATE PRIVATE addition to restrict the instantiation of the classes for cargoplanes and passenger planes. Optionally, move the constructor definitions of both classesto the private section.
2. Use the FRIENDS addition to allow the instantiation of the classes for cargo planes andpassenger planes from inside the factory class.
Hint:You have to use statement CLASS .... DEFINITION DEFERRED beforethe definition of the airplane classes. Otherwise, the factory class or at leastits name is not known to the syntax check when it reaches the FRIENDSaddition.
Task 4
Adjust your main program. Remove the direct instantiations of airplanes and replace them bycalls of the factory method.
1. Replace the instantiations of airplanes with calls of the factory method.
Hint:If you have used exactly the same parameter names as in the constructors,you can keep the parameter passing.
2. Do you have to actually receive the references to the new objects?
Unit 8: Object-Oriented Design Patterns
38 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 393/505
3. Activate, test, and debug your program.
Lesson: Implementing Factory Classes Using Friendship
© Copyright . All rights reserved. 381
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 394/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 395/505
a) You have to type the parameter with the common superclass of cargo planes andpassenger planes, that is, TYPE REF TO lcl_airplane.
See the source text excerpt from the model solution.
Task 2
Implement the factory method. Depending on the optional parameter that is supplied, createeither a cargo plane instance or a passenger plane instance. Define a suitable exception, andraise it if both optional parameters are supplied or none of them.
1. In the factory method, define two local reference variables. Type one with the class forcargo planes (LCL_CARGO_PLANE) and one with the class for passenger planes(LCL_PASSENGER_PLANE).
a) See the source text excerpt from the model solution.
2. Implement an IF-structure in which you analyze the content of the import parameters forcargo and seats. Create either an instance of the cargo plane class or the passenger plane
class. In the case of success, move the reference to the new object to the returningparameter.
a) See the source text excerpt from the model solution.
3. In the definition of the factory class, add two exceptions. One that you raise if a wrongplane type was specified (suggested name: WRONG_PLANETYPE) and one that you raiseif both or none of the optional parameters were supplied (suggested name:WRONG_PARAM_COMBINATION).
a) See the source text excerpt from the model solution.
Task 3
Restrict the creation of cargo planes and passenger planes, so that they can only be createdfrom inside the factory class.
1. Use the CREATE PRIVATE addition to restrict the instantiation of the classes for cargoplanes and passenger planes. Optionally, move the constructor definitions of both classesto the private section.
a) See the source text excerpt from the model solution.
2. Use the FRIENDS addition to allow the instantiation of the classes for cargo planes andpassenger planes from inside the factory class.
Hint:You have to use statement CLASS .... DEFINITION DEFERRED beforethe definition of the airplane classes. Otherwise, the factory class or at leastits name is not known to the syntax check when it reaches the FRIENDSaddition.
a) See the source text excerpt from the model solution.
Task 4
Adjust your main program. Remove the direct instantiations of airplanes and replace them bycalls of the factory method.
Lesson: Implementing Factory Classes Using Friendship
© Copyright . All rights reserved. 383
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 396/505
1. Replace the instantiations of airplanes with calls of the factory method.
Hint:If you have used exactly the same parameter names as in the constructors,you can keep the parameter passing.
a) See the source text excerpt from the model solution.
2. Do you have to actually receive the references to the new objects?
No. Through the message handling implemented earlier, the carrier instance takes care ofall new airplane instances and aggregates them.
3. Activate, test, and debug your program.
a) Carry out this step in the usual manner. For more information, refer to the SAP Library.
Unit 8: Object-Oriented Design Patterns
384 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 397/505
LESSON SUMMARYYou should now be able to:
● Implement friendship relationships
Lesson: Implementing Factory Classes Using Friendship
© Copyright . All rights reserved. 385
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 398/505
Unit 8Lesson 4
364Implementing Persistent Objects
LESSON OVERVIEWThis lesson shows you how to implement persistent objects.
Business Example
You want to use Object Services and Object-Oriented (OO) transactions in your ABAP Objectsprograms. For this reason, you require the following knowledge:
● An understanding of persistence services
● An understanding of persistent classes
● An understanding of how to create persistent objects
● An understanding of how to read persistent objects
● An understanding of how to create OO transactions
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain persistence services
● Examine persistent classes
● Create persistent objects
● Read persistent objects
● Create OO transactions
386 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 399/505
Persistence Services
Figure 144: Simulation of an Object-Oriented Database Management System
Although this technique is not widely used by SAP now and the participants might not plan touse it in their own programs, the agent of the persistent class is a good example for thespecial techniques discussed in the previous lesson.
Make sure you point out the following to the participants:● The abstract CB_... class
● The final CA_... class
● The singleton pattern of the CA_ ... class
● The two factory methods CREATE... and GET...
● The friendship granted by the CL_... class to the CB_... class
● The inheritance of this friendship from the CB_... class to the CA_... class
In principle, ABAP programs work with data and objects that are valid at runtime. The data
and objects used in ABAP programs are transient. It is temporary and disappears when theprogram ends. If you need to store the data permanently and independent of the program,that is persistently, you must store it in a database. Theoretically, you can also use files at theoperating system level.
For this purpose, the persistence services for ABAP Objects were introduced in SAP Web AS6.10. On request, the ABAP developer can define these services and write the currentattribute values of objects as persistent to the associated transparent tables. On receivinganother request, they import these values from the tables again and write the attributes to anobject previously defined as persistent. When doing this, the persistence services use theABAP Open SQL interface.
Lesson: Implementing Persistent Objects
© Copyright . All rights reserved. 387
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 400/505
You will use the persistence services with object-oriented programming techniques. In thisway, you can simulate an object-oriented database management system using a relationaldatabase management system and ABAP Objects.
Persistent Classes
To use the persistence service for objects, you must create their types as persistent classesin Class Builder . The term persistent class indicates that the persistence service manages theinstances of the class and their state. (Global classes are generally persistent. The question iswhether or not their instances are also persistent.)
To ensure that the instances of persistent classes are unique, they should contain keyattributes. You can type these either as worldwide unique identification numbers (objectGUID) or semantic keys.
When you create a persistent class ZCL_<name>, Class Builder automatically generatesmethods for getting and setting its attributes. In addition, the system also generates otherrepository objects, including the class actor (also known as the class agent) ZCA_<name>.
Programs must call the methods of this class to manage the instances of persistent classes,that is, persistent objects. This class also performs the actual database access. Itautomatically inherits the required methods from the basis class ZCB_<name>. You canredefine these methods, if necessary. For example, extend database accesses. The classactor is a singleton instance and has a friendship relationship with the persistent class.
Demonstration: How to Examine a Persistent Class
Show the participants persistent class CL_POB_VEHICLE_TYPE and its agent(CA_POB_VEHICLE_TYPE which inherits from CB_POB_VEHICLE_TYPE). Show how theattributes of the class are linked with the fields of database table SVEHICLE ( Persistencepushbutton). Show the attribute AGENT of CA_POB_VEHICLE_TYPE and the inherited
CREATE_.., GET_..., and DELETE_... methods.
Creation of Persistent Objects
Figure 145: Generating and Writing to Persistent Objects
Unit 8: Object-Oriented Design Patterns
388 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 401/505
In the program, you need to define a reference variable with the type of the class actor and fillit with the reference from the static attribute AGENT. You can then create a new instance ofthe persistent class using its method CREATE_PERSISTENT. The ABAP developer creates itsinterface from the definition of the key attributes of the persistent class. If a persistent objectof the same persistence class with the same key attributes already exists in the program, theclass-based exception CX_OS_OBJECT_EXISTING is triggered. By default, the data is savedby an asynchronous update. You must start this process by using the COMMIT WORKstatement. Thus, the instances of the persistent class do not become persistent objects untilafter that point.
Demonstration: How to Create Persistent Objects
Show the FILL_DBTAB method of the CL_BC401_DEMO_FILL class, which creates severalpersistent objects and stores references to them in the MT_VEHICLE_TYPES table. Explainthat COMMIT WORK is done outside of this method.
Access to Persistent Objects
Figure 146: Reading Persistent Objects
You can load a single persistent object back into a program using the GET_PERSISTENTmethod. When doing so, you must pass the key values to the interface parameters so that youcan uniquely restore the object. If the program does not find the object, it raises the class-
based exception CX_OS_OBJECT_NOT_FOUND.You can retrieve a larger set of persistent objects by using the Query Service . It is possible toprovide a selection, very much like the WHERE-clause of a SELECT statement, as well as theordering criteria.
Demonstration: How to Read a Persistent Object
For a call of the GET_PERSISTENT method, write a small demonstration program. If youwant to demonstrate the use of Query Service, show the READ_DBTAB method of theCL_BC401_DEMO_FILL class. You do not need selection and ordering criteria here, but thecommented coding hints at how you need to use them.
Lesson: Implementing Persistent Objects
© Copyright . All rights reserved. 389
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 402/505
To Create Persistent Classes
The steps to create persistent classes are as follows:
1. Model the class for your persistent objects.
2. Find or create a suitable transparent table that has a field for each attribute of the class. Ifnecessary, adapt the attributes of the class to match the technical field attributes of thetransparent table.
Note:There must be a primary key field in the table for each key attribute of theclass or there must be a key attribute of the class for each primary key field inthe table.
3. In the Class Builder , create a persistent class as described in the SAP Library. Define thepersistence mapping to the table.
OO Transaction
Figure 147: Creating an OO Transaction Code
This section is interesting for two reasons: . The new transaction type has made it possible to develop purely object-oriented
applications, that is, applications with no link to procedural framework programs.
Unit 8: Object-Oriented Design Patterns
39 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 403/505
Caution:You still require procedural framework programs for screen fields.
2. Participants need to learn about the object-oriented transaction services before they canunderstand the OO Transaction Model flag. However, they need to know the OOtransaction as a transaction type before they learn this.
Caution:Breaking these rules will not cause a syntax error or message from theExtended Syntax Check . Instead, you will either cause a runtime error orthere will be no display.
In transaction maintenance , you can create transaction code as an OO transaction. Thismeans that you link the transaction code either to the transaction service of the ABAPObjects services for persistent objects or a public method in a global or local class of aprogram. When calling this type of OO transaction, which is linked to an instance method, thesystem automatically creates an instance of the class in its own internal session and thenexecutes this instance method.
If the OO Transaction Model flag is set, the system links the transaction code to thetransaction service of the ABAP Objects services. Conversely, if it is not set, you can call any
method in a global or local class.Users therefore now have the opportunity to call methods themselves in the usual way (usingmenu options, command field entries, and so on).
Caution:Global classes in ABAP Objects cannot contain screen definitions.
Thus, when you create a link to a global class, note the following:● The constructor cannot contain any IMPORTING parameters.
● You cannot process ABAP list displays.
Therefore, you may have to resort to using methods in local program classes. Naturally, youcan then use all the conventional dialog programming techniques.
To Create OO Transactions
You can create an OO transaction by using the following steps:
1. Call the usual dialog for creating transaction code and enter a short text.
2. Choose the Method of a Class (OO Transaction) option as an Initial Object.
Lesson: Implementing Persistent Objects
© Copyright . All rights reserved. 391
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 404/505
3. Leave the OO Transaction Model flag unchecked if you want to link the transaction code toa normal instance method.
4. Enter the Class Name and Method . Set the Local in Program flag and enter the programname, if you are using a local class.
5. Save the transaction code.
Demonstration: Create an OO Transaction
Either create your own demonstration or use transaction BC401_DEMO_FILL as an example.The transaction points to the MAIN instance method of the CL_BC401_DEMO_FILL class.Consequently, the system instantiates the class when you invoke the transaction.Demonstrate this with a break point in the class’s instance constructor.
If there is enough time and the participants show sufficient interest, you can analyze theSTART_TRANSACTION and END_TRANSACTION methods to give them a rough idea of howOO Transaction Model works. It could be worth mentioning that in OO Transaction Model,transactions can be nested. Calling the END method commits on the database only if it is top-
level transaction.
Note:There is a plan to include a detailed discussion on creating OO Transaction inthe next version of the BC414 Programming Database Updates course.
LESSON SUMMARYYou should now be able to:
● Explain persistence services
● Examine persistent classes
● Create persistent objects
● Read persistent objects
● Create OO transactions
Unit 8: Object-Oriented Design Patterns
392 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 405/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 406/505
5. If the instance constructor is protected, the visibility is extended to all of its subclasses.
Determine whether this statement is true or false.
X True
X False
6. Which of the following are the advantages of factory method?
Choose the correct answers.
X A A factory method can have coding that is executed before the actual instantiation.
X B A class can have more than one factory method with different implementation andsignature.
X C Factory methods cannot be used to administrate the instances of a class within the
class itself.
X D A factory method cannot be used to instantiate one of the subclasses rather thanthe class itself.
7. Which of the following is done using the singleton concept?
Choose the correct answers.
X A Preventing a class from being instantiated more than once for the same programcontext
X B Restricting the visibility of the instance constructor
X C Keeping a reference to all its instances in a static attribute
X D Storing only one instance instead of storing several instances
8. Which of the following concepts is used to provide a class access to the privatecomponents of the other class?
Choose the correct answer.
X A Singleton
X B Friendship
X C Interface
X D Casting
Unit 8: Learning Assessment
394 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 407/505
9. ABAP programs work with data and objects that cannot be stored permanently.
Determine whether this statement is true or false.
X True
X False
10. You use the persistence services with object-oriented programming techniques.
Determine whether this statement is true or false.
X True
X False
11. What should you do to use the persistence service for objects?
Choose the correct answer.
X A You must type it as an object GUID.
X B You must type it as a semantic key.
X C You must create their types as persistent classes in the Class Builder.
12. What should you do to ensure that the instances of persistent classes are unique?
Choose the correct answers.
X A You must store them in a database.
X B You must type it as an object GUID.
X C You must type it as a semantic key.
X D You must create their types as persistent classes in the Class Builder.
13. Which class-based exception is triggered if a persistent object of the same persistenceclass with the same key attributes already exists in the program?
Choose the correct answer.
X A The CREATE_PERSISTENT method
X B The AGENT attribute
X C The CX_OS_OBJECT_EXISTING class-based exception
X D The COMMIT WORK statement
Unit 8: Learning Assessment
© Copyright . All rights reserved. 395
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 408/505
14. How can you create a new instance of the persistent class?
Choose the correct answer.
X A By using the CREATE_PERSISTENT method
X B By using the AGENT attribute
X C By using the CX_OS_OBJECT_EXISTING class-based exception
X D By using the COMMIT WORK statement
15. How can you load a single persistent object back into a program?
Choose the correct answer.
X A By using the CREATE_PERSISTENT method
X B By using the CX_OS_OBJECT_EXISTING class-based exception
X C By using the Query Service
X D By using the GET_PERSISTENT method
16. How can you retrieve a larger set of persistent objects?
Choose the correct answer.
X A By using the Query Service
X B By using the CREATE_PERSISTENT method
X C By using the CX_OS_OBJECT_EXISTING class-based exception
X D By using the GET_PERSISTENT method
17. What happens if the OO Transaction Model flag is not set?
Choose the correct answer.
X A Create a transaction code as an OO transaction.
X B System links the transaction code to the transaction service of the ABAP Objectsservices.
X C Call any method in a global or local class.
X D Link the transaction code to the transaction service of the ABAP Objects servicesfor persistent objects.
Unit 8: Learning Assessment
396 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 409/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 410/505
Unit 8
376Learning Assessment- Answers
1. Static _____________ cannot be abstract because they cannot be redefined.
Choose the correct answer.
X A class
X B structure
X C method
X D attribute
2. You can prevent a class from being inherited by using the final addition with the classstatement.
Determine whether this statement is true or false.
X True
X False
3. By making the key attributes __________, we can avoid the redundant storage ofinformation.
Choose the correct answer.
X A public
X B private
X C protected
4. An association means that at runtime an instance of one class stores references toobjects of another class.
Determine whether this statement is true or false.
X True
X False
398 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 411/505
5. If the instance constructor is protected, the visibility is extended to all of its subclasses.
Determine whether this statement is true or false.
X True
X False
6. Which of the following are the advantages of factory method?
Choose the correct answers.
X A A factory method can have coding that is executed before the actual instantiation.
X B A class can have more than one factory method with different implementation andsignature.
X C Factory methods cannot be used to administrate the instances of a class within theclass itself.
X D A factory method cannot be used to instantiate one of the subclasses rather thanthe class itself.
7. Which of the following is done using the singleton concept?
Choose the correct answers.
X A Preventing a class from being instantiated more than once for the same programcontext
X B Restricting the visibility of the instance constructor
X C Keeping a reference to all its instances in a static attribute
X D Storing only one instance instead of storing several instances
8. Which of the following concepts is used to provide a class access to the privatecomponents of the other class?
Choose the correct answer.
X A Singleton
X B Friendship
X C Interface
X D Casting
Unit 8: Learning Assessment- Answers
© Copyright . All rights reserved. 399
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 412/505
9. ABAP programs work with data and objects that cannot be stored permanently.
Determine whether this statement is true or false.
X True
X False
10. You use the persistence services with object-oriented programming techniques.
Determine whether this statement is true or false.
X True
X False
11. What should you do to use the persistence service for objects?Choose the correct answer.
X A You must type it as an object GUID.
X B You must type it as a semantic key.
X C You must create their types as persistent classes in the Class Builder.
12. What should you do to ensure that the instances of persistent classes are unique?
Choose the correct answers.
X A You must store them in a database.
X B You must type it as an object GUID.
X C You must type it as a semantic key.
X D You must create their types as persistent classes in the Class Builder.
13. Which class-based exception is triggered if a persistent object of the same persistenceclass with the same key attributes already exists in the program?
Choose the correct answer.
X A The CREATE_PERSISTENT method
X B The AGENT attribute
X C The CX_OS_OBJECT_EXISTING class-based exception
X D The COMMIT WORK statement
Unit 8: Learning Assessment- Answers
4 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 413/505
14. How can you create a new instance of the persistent class?
Choose the correct answer.
X A By using the CREATE_PERSISTENT method
X B By using the AGENT attribute
X C By using the CX_OS_OBJECT_EXISTING class-based exception
X D By using the COMMIT WORK statement
15. How can you load a single persistent object back into a program?
Choose the correct answer.
X A By using the CREATE_PERSISTENT method
X B By using the CX_OS_OBJECT_EXISTING class-based exception
X C By using the Query Service
X D By using the GET_PERSISTENT method
16. How can you retrieve a larger set of persistent objects?
Choose the correct answer.
X A By using the Query Service
X B By using the CREATE_PERSISTENT method
X C By using the CX_OS_OBJECT_EXISTING class-based exception
X D By using the GET_PERSISTENT method
17. What happens if the OO Transaction Model flag is not set?
Choose the correct answer.
X A Create a transaction code as an OO transaction.
X B System links the transaction code to the transaction service of the ABAP Objectsservices.
X C Call any method in a global or local class.
X D Link the transaction code to the transaction service of the ABAP Objects servicesfor persistent objects.
Unit 8: Learning Assessment- Answers
© Copyright . All rights reserved. 4 1
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 414/505
18. In transaction maintenance, you can only link the transaction code to the transactionservice of the ABAP Objects services for persistent objects.
Determine whether this statement is true or false.
X True
X False
Unit 8: Learning Assessment- Answers
4 2 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 415/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 416/505
Unit 9Lesson 1
382Explaining Class-Based Exception Handling
LESSON OVERVIEWThis lesson explains class-based exception handling.
It is particularly important to point out that these are enhancements of the existing featuresof ABAP Objects. Naturally, the old exceptions concept can still be used but it will no longerbe developed.
Participants with experience in Java will notice marked similarities in syntax and runtime
behavior. The main point again is to present the additional user-friendly options available inABAP Objects and the ABAP Workbench.
In the unlikely event that participants are still skeptical about object-oriented programming, itmay be helpful to motivate them with a simple example from procedural programming. Untilnow, subroutines could not raise exceptions that could be handled. Instead, you had toimplement a relationship check yourself, using EXIT or RETURN as of SAP Web AS 6.10 andauxiliary variables that you had to define. Now, any processing block in ABAP Objects canraise a class-based exception.
Business Example
You should use the new exceptions concept in your ABAP Object programs. For this reason,you require the following knowledge:
● An understanding of class-based exceptions
● An understanding of handling class-based exceptions
● An understanding of debugging class-based exceptions
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain class-based exceptions
● Handle class-based exceptions
● Debug class-based exceptions
4 4 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 417/505
Class-Based Exceptions
Figure 148: An Overview of the Class-Based Exception Concept
With this graphic, mention that exceptions are not always triggered explicitly by a RAISE callas shown in the example, but also implicitly by using a zero division of the runtime system. Todemonstrate this, program a zero division and point out the exception class displayed in thedump. You should perhaps also mention the ST22 or the syslog SM21, if known.
We use the term exception to refer to a situation that arises while a program is beingexecuted, where there is no point in continuing to run the program in the normal way. SAPWeb AS 6.10 introduced a new ABAP Objects exception concept, parallel to the existingconcept based on sy-subrc. Exceptions and exception handling are now based on classes.This new ABAP Objects exception concept includes the concepts based on sy-subrc thatpreceded it but also enhances and thus replaces them.
Hint:Note that the use of class-based exceptions is not limited to object-orientedcontexts. Class-based exceptions can be raised and handled in all processing
blocks. In particular, all previously catchable runtime errors can now be handledas class-based exceptions.
In the new exception concept, an exception is represented by an exception object. Anexception object is an instance of an exception class. The attribute values of the exceptionobject contain information about the respective error situation. Raising a class-basedexception normally means instantiating an exception class and setting the attributes.Handling a class-based exception normally means getting access to the exception object andevaluating its attribute values.
Class-based exceptions are raised either by the RAISE EXCEPTION statement or by theruntime environment. They are caught and handled with the TRY...CATCH...ENDTRYstructure.
Lesson: Explaining Class-Based Exception Handling
© Copyright . All rights reserved. 4 5
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 418/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 419/505
Class-Based Exception Handling
Figure 150: Structure of a TRY-ENDTRY Block
An exception can only be handled if the statement that raised it is enclosed in a TRY-ENDTRYcontrol structure. The exception is then handled using the CATCH statement in the TRY-ENDTRY structure.
The TRY block contains the statements for which the exceptions should be handled. A CATCHblock contains the exception handler that is executed if a specified exception has occurred inthe associated TRY block.
Like all control structures in ABAP Objects, TRY-ENDTRY structures can be nested to anydepth. In particular, the TRY block, CATCH block, and the CLEANUP block can containcomplete TRY-ENDTRY structures themselves.
You can specify any number of exception classes to the CATCH statement. In this way, youdefine an exception handler for all these exception classes and their subclasses.
If an exception occurs, the system searches first for a matching CATCH statement in the TRY-ENDTRY structure that immediately surrounds the statement. It searches through its CATCHblocks in the order specified. A matching CATCH statement mentions either the exceptionclass itself or one of its superclasses. If it finds one, it leaves the TRY block and navigatesdirectly to this handler.
If it does not find one, the system gradually searches outwards in all the surrounding TRY-ENDTRY structures. If it cannot find a handler within the same procedure, the system tries topropagate the exception to the calling program. This will be discussed in more detail later.
If a TRY-ENDTRY structure contains a CLEANUP block, this block is executed when the TRY-ENDTRY structure is exited because the system cannot find a handler within the TRY-ENDTRY structure itself but in a surrounding TRY-ENDTRY structure or in a calling program.
Lesson: Explaining Class-Based Exception Handling
© Copyright . All rights reserved. 4 7
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 420/505
Example Syntax for Handling Predefined Exceptions
Figure 151: Example Syntax for Handling Predefined Exceptions
The figure gives an example of syntax for handling predefined exceptions.
To analyze the exception object in an exception handler, you have to use the CATCHstatement in the form CATCH ... INTO ... After the optional addition INTO, you have to specifya suitably typed object reference. This can either be a reference to the exception class itself orto any of its superclasses. Just before the CATCH block is executed, the system will fill this
reference variable so that it points to the exception object describing the present errorsituation.
If the value range for I data type is exceeded in the calculation, the runtime system raises theexception CX_SY_ARITHMETIC_OVERFLOW. This exception is handled in the implementedCATCH block. The reference to the appropriate instance is stored in the data object GO_EXC.The handler can access the instance’s exception text using the functional method GET_TEXT.The text is stored in the data object GV_TEXT with the type STRING and then displayed as aninformation message.
Of course, any other public component of the exception object could also be accessed duringexception handling. But this depends, as usual, on the static type of the reference variable. Inthe example above, the reference variable is typed as REF TO CX_ROOT, which restrictsaccess to the components defined in CX_ROOT. If you want to access the more-specificcomponents of the exception object, you need a more-specific type for the reference variable.Other options would have been the superclass CX_SY_ARITHMETIC_ERROR and the super-superclass CX_DYNAMIC_CHECK.
The ABAP keyword documentation for each statement lists the classes whose exceptions mayoccur when that statement is executed.
Demonstration: How to Handle Class-Based Exceptions
To demonstrate different aspects of the TRY control structure, you can explain and debugprograms SAPBC401_EXC_TRY_D1 ... SAPBC401_EXC_TRY_D5, which you find in package
BC401.
Unit 9: Object-Oriented Exception Handling
4 8 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 421/505
The table showing the TRY-ENDTRY control structure is as follows:
Program Name Program Structure
SAPBC401_EXC_TRY_D1 TRY with direct CATCH of an exception
SAPBC401_EXC_TRY_D2 TRY with CATCH of a superclassSAPBC401_EXC_TRY_D3 Nested TRY structure
SAPBC401_EXC_TRY_D4 CLEANUP in nested TRY structures
Analysis of Class-Based Exceptions in the Debugger
Figure 152: Class-Based Exceptions in Debugging Mode
If an exception is raised, the name of the exception class is displayed in the Exception Raisedfield in debugging mode.
If this exception is caught using a CATCH block, this is displayed in the form of a success
message. The pointer for the current statement then moves to this CATCH block.Two pushbuttons appear if an exception occurred. They allow you to analyze the exceptionobject and to navigate to the point in the source code where the exception occurred.
Hint:For performance reasons, the system does not actually create exception objectsif the INTO addition is missing from the respective CATCH statement. In suchcases, the Last Exception Object pushbutton will normally not appear.
You can make the ABAP Debugger always create the exception object bychoosing the respective option in the debugger settings.
Lesson: Explaining Class-Based Exception Handling
© Copyright . All rights reserved. 4 9
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 422/505
Regarding the creation of global exception classes, a few changes have been made to SAPNW AS 6.40.
The texts within the exception classes were stored beforehand in the Online Text Repository(OTR). When you created a text under the Texts tab page, the system always asked for an IDunder which to store the text in the OTR or the easiest thing to do was to use the exception ID
here. Test this procedure before the course begins in a system with a release level before6.40, so that you can respond to any questions that may arise.
For didactic reasons, it is recommended that you address the above mentioned points at theend of the topic so that the participants do not get confused. It should be sufficient to brieflymention how the above concept worked before Release 6.40.
LESSON SUMMARYYou should now be able to:
● Explain class-based exceptions
●
Handle class-based exceptions● Debug class-based exceptions
Unit 9: Object-Oriented Exception Handling
41 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 423/505
Unit 9Lesson 2
388Defining and Raising Exceptions
LESSON OVERVIEWThis lesson explains how to define and raise global exception classes.
Business Example
You should now define global exception classes for your ABAP Object programs. For thisreason, you require the following knowledge:
● Definition of global exception classes
● Raising of class-based exceptions
● How to implement exception propagation
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Define global exception classes
● Raise class-based exceptions
● Propagate exceptions
© Copyright . All rights reserved. 411
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 424/505
Definition of Global Exception Classes
Figure 153: Creating Global Exception Classes
In Class Builder , create a global class as described in SAP Library. When you enter its name,use the prefix CX_. Choose the Exception Class option as the class type.
Note:As of SAP NW AS 6.40, you can still select the with Message Class checkbox whenyou create an exception class. Later, the texts that should appear whenexceptions occur can be taken from the messages classes identified in themessage statement. You will find these known messages and message classes inT100 table.
In releases before SAP NW AS 6.40, the exception texts were stored solely inOnline Text Repository (OTR).
When you create the exception class, do not change the default entry for Inheritsfrom unless you are fully aware of the consequences of making the change.
Define additional attributes in your exception class, if necessary (for example, for genericextensions to exception texts).
Unit 9: Object-Oriented Exception Handling
412 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 425/505
Hint:If such an attribute is public, the Class Builder automatically adjusts the instanceconstructor of the exception class.
A new input parameter is generated using which a value can be set for thisattribute when raising the exception. The import parameter is generated with thesame name as the attribute. By default, the parameter is optional. You maydeclare it mandatory by editing the constructor’s signature.
Define Variable Exception Texts
Figure 154: Define Variable Exception Texts
Save as many exception texts as you need. When you do so, you can insert your attributes asparameters in the static text in the form &<attribute_name>&.
Note:
For the first text you create, always use a predefined static constant as an ID. Thetext always has the same name as the exception class itself. If no text is specifiedexplicitly when the exception is raised, the text with this ID is used instead.
For all other texts, define other IDs. Class Builder then generates identically named staticconstants automatically. When the exception is raised, you pass one of these constants to theimport parameter TEXTID to specify the appropriate text for the exception instance.
Lesson: Defining and Raising Exceptions
© Copyright . All rights reserved. 413
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 426/505
Note:The exception texts for global exception classes and their translations are storedin OTR in releases before SAP NW AS 6.40. Note that several texts can beassigned to a single class. You assign a text to an exception using the TEXTID
attribute, which contains the globally unique ID of the text object in OTR in aninstance at run time. The GET_TEXT method then exports this text, replaces anytext parameters with the contents of the relevant attributes as required, andreturns the text as a character string.
Activate the exception class.
To Define Global Exception ClassesYou can create and define global exception classes.
The steps to define global exception classes are as follows:
1. In the Class Builder , create a global class as described in the SAP Library. When you enterits name, use the prefix CX_. Choose the Exception Class option as the Class Type .
2. Define additional attributes in your exception class, if necessary (for example, for genericextensions to exception texts).
3. Save as many exception texts as you need. When you do so, you can insert your attributesas parameters in the static text in the form &<attribute_name>&.
For all other texts, define other IDs. Class Builder then generates identically named staticconstants automatically. When the exception is raised, you pass one of these constants tothe import parameter TEXTID to specify the appropriate text for the exception instance.
4. Activate the exception class.
Raising of Class-Based Exceptions
Figure 155: Variants of Statement RAISE EXCEPTION
Unit 9: Object-Oriented Exception Handling
414 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 427/505
The figure shows an example for each variant.
Raising class-based exceptions is done using the RAISE EXCEPTION statement. There aretwo variants of the statement.
RAISE EXCEPTION TYPE <exception_class> [EXPORTING ...] .
This statement creates a new exception object that is an instance of the <exception_class>class.
RAISE EXCEPTION <object_ref> .
This statement uses an existing exception object that the one <object_ref> points to.
The exception object was either created directly using a CREATE OBJECT statement or, morecommonly, caught in a previous CATCH ... INTO ...statement and now should be passed on.
When using the first variant, it is possible to provide values for the constructor parametersusing the EXPORTING addition. One of these parameters is used to set the exception text inthe new exception object.
Set Exception Text
Figure 156: Setting the Exception Text
All exception classes offer an optional parameter TEXTID in their constructors. Thisparameter is used if more than one message text is available in the exception class and youdo not want to raise the exception with the default text.
For each text defined on the Texts tab, the Class Builder generates a public constant of thesame name. Other such constants might also be inherited from the superclasses of theexception class.
By default, the exception is raised with the text that has the same name as the exceptionclass. To raise the exception with another text, you have to use the corresponding constant asthe actual parameter for constructor parameter TEXTID.
Lesson: Defining and Raising Exceptions
© Copyright . All rights reserved. 415
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 428/505
Note:The type of the constants and parameter TEXTID in the constructor depends onwhether or not the exception class was created with the With message class flag.If the exception class still uses OTR texts, the constants are of type CHAR and
contain a technical ID of the OTR text. If the exception class uses a message class,the constants are structures containing the name of the message class, themessage number, and so on.
Exception Propagation
Figure 157: Propagating Class-Based Exceptions
Exceptions that occur in procedures do not necessarily need to be handled where they occur.They can be propagated to the caller of the procedure. The caller can then handle theexception or propagate it to its own caller, and so on. The highest levels to which an exceptioncan be propagated are processing blocks without local data areas, that is, event blocks ordialog modules. You must deal with the exceptions propagated by the called procedures asyou will deal with any exceptions raised within this processing block itself. Otherwise, aruntime error occurs.
To propagate an exception from a procedure, you generally use the RAISING addition whenyou are defining the procedure interface. In methods of local classes and subroutines, specifythe RAISING addition directly when you are defining the procedure. For example:
METHODS meth_name ... RAISING cx_... cx_... or FORM subr_name ...RAISING cx_... cx_....
After RAISING statement addition, list the exception classes whose instances are to bepropagated. In methods of global classes, the exception classes whose instances are to bepropagated are entered in the exception table of the method in the Class Builder . You alsoneed to set the Exception Class flag for each exception table. The process is similar forfunction modules. To set the indicator in Function Builder , choose the Exceptions tab.
Unit 9: Object-Oriented Exception Handling
416 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 429/505
Hint:Note that a single method, form, or function module can raise only one type ofexception, class-based or conventional.
Propagating Exceptions Over Several Hierarchy – Levels
Figure 158: Propagating Exceptions Over Several Hierarchy – Levels
Propagation of class-based exception does not require that the exception actually to behandled by the calling method. The caller may pass on the exception to its own caller withouteven looking at it.
In the example, the constructor propagates the CX_EXC exception raised by theGET_TECH_ATTR method. When the exception is raised, the program flow jumps directly tothe CATCH block in the main program.
Note:
If the constructor implements the optional CLEANUP block, this block is executedbefore the CATCH block of the main program.
We advise you to have the participants do the exercise on defining, raising,propagating, and handling class-based exceptions at this point.
Demonstration: How to Implement Exception Propagation
To demonstrate the different aspects of exception propagation, you can explain and debugprograms SAPBC401_EXC_PROP_D1 ... SAPBC401_EXC_PROP_D3, which you can find inpackage BC401 .
Lesson: Defining and Raising Exceptions
© Copyright . All rights reserved. 417
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 430/505
The following table lists the different aspects of exception propagation:
Program Purpose
SAPBC401_EXC_PROP_D1 Raise an exception in a method(constructor), propagate it, and handle it in
the immediate caller.
SAPBC401_EXC_ PROP _D2 Raise an exception in a method withget_technical attributes, propagate itthrough several call hierarchies, and handleit in the top level of the main program.
SAPBC401_EXC_ PROP _D3 This will be same as _EXC_PROP_D3 butwith a CLEANUP block in the middlemethod of the constructor.
Unit 9: Object-Oriented Exception Handling
418 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 431/505
Unit 9Exercise 23
395Implement Class-Based Exceptions
Task 1
Create a global exception class for an invalid airplane type.
1. Create a global exception class called ZCX_##_INVALID_PLANETYPE (where ## is yourtwo-digit group number).
You want the syntax check to make sure that exceptions based on this class are eitherhandled directly or propagated. Choose the superclass accordingly.
In the exception class, you want to use texts from a message class instead of freelydefined texts.
Hint:Whether or not the messages from a message class are used must be statedright during the creation of the exception class by selecting the MessageClass checkbox.
2. Add an attribute for the airplane type (suggested name: PLANETYPE) and assign the typeS_PLANETYPE to it. Make sure a corresponding parameter is defined in the signature ofthe constructor.
Hint:Note that you cannot define the constructor of an exception class directly. Ifyou define the attribute as public, a corresponding import parameter is addedto the constructor by the framework.
3. Create a default error message. The message text should include a placeholder so that itcan be enhanced dynamically to include the airplane type.
Hint:You can define your own message class and message or use message 020from BC401 message class.
Task 2
Raise your new exception in the GET_TECHNICAL ATTRIBUTES method of your local classLCL_AIRPLANE.
1. Complete your ZBC401_##_MAIN program or copy the template program.
© Copyright . All rights reserved. 419
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 432/505
2. Edit the definition of local class LCL_AIRPLANE. Remove the classical, non class-basedexception WRONG_PLANETYPE from the signature of methodGET_TECHNICAL_ATTRIBUTES and replace it with your new class-based exceptionZCX_##_INVALID_PLANETYPE.
3. Edit the implementation of method GET_TECHNICAL_ATTRIBUTES and raise the class-
based exception instead of the classical exception. Make sure the wrong plane type valueis handed over to the constructor and stored in the exception object.
Task 3
Explicitly propagate the class-based exception through the entire call hierarchy so that youmust handle it only once in the main program.
1. Edit the definition of LCL_AIRPLANE. Remove the classical, non class-based exceptionWRONG_PLANETYPE from the signature of method GET_TECHNICAL_ATTRIBUTES andreplace it with your new class-based exception ZCX_##_INVALID_PLANETYPE.
2. Edit the implementation of the constructor of local class LCL_AIRPLANE. While callingmethod GET_TECHNICAL_ATTRIBUTES, remove the handling of classical exceptionWRONG_PLANETYPE.
3. Why is it not necessary to handle the class-based exceptionZCX_##_INVALID_PLANETYPE here?
4. Edit the definition of local class LCL_PASSENGER_PLANE. Remove the classical, nonclass-based exception WRONG_PLANETYPE from the signature of the CONSTRUCTORmethod and replace it with your new class-based exceptionZCX_##_INVALID_PLANETYPE.
Edit the implementation of the constructor of local class LCL_PASSENGER_PLANE. In thecall of SUPER->CONSTRUCTOR, remove the handling of classical exceptionWRONG_PLANETYPE.
5. Repeat the previous steps with local class LCL_CARGO_PLANE.
Task 4
Handle the raised exception in the main program whenever an airplane object is created.
1. Define a global reference variable for this purpose (suggested name:GO_INV_PLANETYPE) and type it with your exception classZCX_##_INVALID_PLANETYPE.
2. In the CREATE OBJECT statement for airplanes (instances of LCL_AIRPLANE,LCL_PASSENGER_PLANE, and LCL_CARGO_PLANE), remove the handling of theclassical, non class-based exception WRONG_PLANETYPE.
3. Surround each CREATE OBJECT statement for airplanes with a TRY-ENDTRY structure.Add a CATCH block for your exception ZCX_##_INVALID_PLANETYPE. In the case of anexception, let reference variable GO_INV_PLANETYPE point to the exception object.
4. Read the error text from the exception object and output it to the ABAP list.
Unit 9: Object-Oriented Exception Handling
42 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 433/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 434/505
Unit 9Solution 23
398Implement Class-Based Exceptions
Task 1
Create a global exception class for an invalid airplane type.
1. Create a global exception class called ZCX_##_INVALID_PLANETYPE (where ## is yourtwo-digit group number).
You want the syntax check to make sure that exceptions based on this class are eitherhandled directly or propagated. Choose the superclass accordingly.
In the exception class, you want to use texts from a message class instead of freelydefined texts.
Hint:Whether or not the messages from a message class are used must be statedright during the creation of the exception class by selecting the MessageClass checkbox.
a) Create a global class.
b) On the following window, choose the CX_STATIC_CHECK superclass.
c) Choose the Exception Class option and select the Message Class checkbox.Speak to your instructor if you have any questions.
2. Add an attribute for the airplane type (suggested name: PLANETYPE) and assign the typeS_PLANETYPE to it. Make sure a corresponding parameter is defined in the signature ofthe constructor.
Hint:Note that you cannot define the constructor of an exception class directly. Ifyou define the attribute as public, a corresponding import parameter is addedto the constructor by the framework.
a) Go to the Attributes tab. Enter the attribute name and type and choose the visibility.
Speak to your instructor if you have any questions.
3. Create a default error message. The message text should include a placeholder so that itcan be enhanced dynamically to include the airplane type.
Hint:You can define your own message class and message or use message 020from BC401 message class.
422 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 435/505
a) Go to the Texts tab. Select the default text and choose Message Text .
b) Enter the message class and message number in the relevant fields. In the Attr. 1 field,use the value that helps to choose the PLANETYPE attribute.
Speak to your instructor if you have any questions.
Task 2
Raise your new exception in the GET_TECHNICAL ATTRIBUTES method of your local classLCL_AIRPLANE.
1. Complete your ZBC401_##_MAIN program or copy the template program.
a) Carry out this step in the usual manner. Additional information is available in SAPLibrary.
2. Edit the definition of local class LCL_AIRPLANE. Remove the classical, non class-basedexception WRONG_PLANETYPE from the signature of method
GET_TECHNICAL_ATTRIBUTES and replace it with your new class-based exceptionZCX_##_INVALID_PLANETYPE.
a) See the source code extract from the model solution.
3. Edit the implementation of method GET_TECHNICAL_ATTRIBUTES and raise the class-based exception instead of the classical exception. Make sure the wrong plane type valueis handed over to the constructor and stored in the exception object.
a) See the source code extract from the model solution.
Task 3
Explicitly propagate the class-based exception through the entire call hierarchy so that youmust handle it only once in the main program.
1. Edit the definition of LCL_AIRPLANE. Remove the classical, non class-based exceptionWRONG_PLANETYPE from the signature of method GET_TECHNICAL_ATTRIBUTES andreplace it with your new class-based exception ZCX_##_INVALID_PLANETYPE.
a) See the source code extract from the model solution.
2. Edit the implementation of the constructor of local class LCL_AIRPLANE. While callingmethod GET_TECHNICAL_ATTRIBUTES, remove the handling of classical exceptionWRONG_PLANETYPE.
a) See the source code extract from the model solution.
3. Why is it not necessary to handle the class-based exceptionZCX_##_INVALID_PLANETYPE here?
It is because this exception is propagated in the signature of the constructor ofLCL_AIRPLANE.
4. Edit the definition of local class LCL_PASSENGER_PLANE. Remove the classical, nonclass-based exception WRONG_PLANETYPE from the signature of the CONSTRUCTORmethod and replace it with your new class-based exceptionZCX_##_INVALID_PLANETYPE.
Lesson: Defining and Raising Exceptions
© Copyright . All rights reserved. 423
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 436/505
Edit the implementation of the constructor of local class LCL_PASSENGER_PLANE. In thecall of SUPER->CONSTRUCTOR, remove the handling of classical exceptionWRONG_PLANETYPE.
a) See the source code extract from the model solution.
5. Repeat the previous steps with local class LCL_CARGO_PLANE.
a) See the source code extract from the model solution.
Task 4
Handle the raised exception in the main program whenever an airplane object is created.
1. Define a global reference variable for this purpose (suggested name:GO_INV_PLANETYPE) and type it with your exception classZCX_##_INVALID_PLANETYPE.
a) See the source code extract from the model solution.
2. In the CREATE OBJECT statement for airplanes (instances of LCL_AIRPLANE,LCL_PASSENGER_PLANE, and LCL_CARGO_PLANE), remove the handling of theclassical, non class-based exception WRONG_PLANETYPE.
a) See the source code extract from the model solution.
3. Surround each CREATE OBJECT statement for airplanes with a TRY-ENDTRY structure.Add a CATCH block for your exception ZCX_##_INVALID_PLANETYPE. In the case of anexception, let reference variable GO_INV_PLANETYPE point to the exception object.
a) See the source code extract from the model solution.
4. Read the error text from the exception object and output it to the ABAP list.
Hint:It is not possible to use the result of functional methods directly in the WRITEstatement. You need to define a variable to store the text (suggested name:GV_TEXT with data type STRING).
a) See the source code extract from the model solution.
5. Activate and test your program. For test purposes, create an airplane with a wrong planetype and debug the propagation of the exception.
a) Perform this step in the usual manner.
Unit 9: Object-Oriented Exception Handling
424 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 437/505
LESSON SUMMARYYou should now be able to:
● Define global exception classes
● Raise class-based exceptions
● Propagate exceptions
Lesson: Defining and Raising Exceptions
© Copyright . All rights reserved. 425
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 438/505
Unit 9Lesson 3
402Implementing Advanced Exception Handling
Techniques
LESSON OVERVIEWThis lesson explains the implementation of advanced exception handling techniques.
Business Example
As a developer, use the advanced exception handling techniques for catching the exceptions.
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain the hierarchy of predefined exception classes
● Explain different ways of handling an exception
● Retry after exceptions
● Implement resumable exceptions
● Reraise exceptions
● Map exceptions to each other
The Hierarchy of Predefined Exception Classes
Figure 159: Propagating Exceptions over Several Hierarchy-Levels
426 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 439/505
We advise you to have the participants do the exercise on defining, raising, propagating, andhandling class-based exceptions at this point.
Propagation of class-based exception does not require that the exception actually handled bythe calling method. The caller may pass on the exception to its own caller without evenlooking at it. In the example, the constructor propagates the exception CX_EXC, which israised by method GET_TECH_ATTR. When the exception is raised, the program flow jumpsdirectly to the CATCH block in the main program.
Note:If the constructor had implemented the optional CLEANUP block, this block wouldbe executed before the CATCH block of the main program.
Integration of Standard Exceptions in the Runtime System
Figure 160: Integration of Standard Exceptions in the Runtime System
The figure explains consequences that arise from the choice of an exception class’ssuperclass. It also shows how the exceptions in the runtime system were integrated into theinheritance hierarchy of the exception classes.
The choice of the superclass has an influence on the way a given exception is handled by thesyntax check as well as by the runtime environment.
If an exception class inherits directly or indirectly from CX_STATIC_CHECK, the relevantexception must either be handled, or propagated using the RAISING addition. If this is not thecase, the syntax check displays a warning. When defining new global exception classes,CX_STATIC_CHECK is defined as the superclass by default.
For subclasses of CX_DYNAMIC_CHECK, there will be no warning from the syntax check if
they are neither handled nor propagated with the RAISING addition.
Lesson: Implementing Advanced Exception Handling Techniques
© Copyright . All rights reserved. 427
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 440/505
But if an exception is raised at runtime and it is neither handled nor propagated, the systemwill end the program with a runtime error.
Note:Typical examples of this situation are the predefined exceptions CX_SY_... forerrors that occur in the runtime environment. These are usually subclasses ofCX_DYNAMIC_CHECK.
For subclasses of CX_NO_CHECK, the corresponding exceptions cannot be propagatedexplicitly using the RAISING addition. If such exceptions are not handled in the processingblock where they occur, they are automatically propagated. If they are not handled by thecalling processing block, they are automatically propagated further on to the highest callhierarchy level. If they are not handled on the top level, a runtime error will occur at the pointwhere they were raised.
Some predefined exceptions with the prefix CX_SY_... for error situations in the runtime
environment are subclasses of CX_NO_CHECK.
Different Ways of Handling an Exception
To demonstrate different aspects of the exception handling, you can explain and debugprograms SAPBC401_EXC_CATCH_D1 ... SAPBC401_EXC_CATCH_D4, which you find inBC401 package.
The following are the purpose of the programs:
Program Purpose
SAPBC401_EXC_CATCH_D1 RETRY: Handle an exception, remove the
cause, and repeat the complete TRY BlockSAPBC401_EXC_CATCH_D2 RESUME: Raise and propagate a resumable
exception. Handle it, retaining the contextand eventually resume execution right afterthe exception
SAPBC401_EXC_CATCH_D3 Handle an exception in middle method(constructor) and reraise it using RAISEEXCEPTION <object_ref>
SAPBC401_EXC_CATCH_D4 Handle an exception in middle method(constructor), raise a new exception, and
chain the exception objects via thePREVIOUS attribute
After an exception was caught in a CATCH statement, there are different ways to handle itbesides stopping the program.
The different ways to handle the exception are as follows:1. Continue program behind ENTRY statement after
● Ignoring the exception (do nothing)
● Issuing a warning
Unit 9: Object-Oriented Exception Handling
428 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 441/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 442/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 443/505
Hint:Respective checkboxes are available in Class Builder and Function Builderwhen defining the signature of a method or the interface of a functionmodule.
The handler of a given exception is able to find out at runtime whether a given exception wasraised and propagated resumable or not. All exception objects provide the public instanceattribute IS_RESUMABLE, which is set to ’X’ or ’ ’ by the framework, depending on how theexception was raised and propagated. Resuming a non resumable exception will cause aruntime error (exception class CX_SY_ILLEGAL_HANDLER).
Resume Execution After a Resumable Exception
Figure 163: Resume Execution After a Resumable Exception
In the example, the exception is raised and propagated by method GET_TECH_ATTR andfurther propagated by the constructor. All raising and propagating is resumable. The mainprogram handles the exception with CATCH BEFORE UNWIND ..., checks that the exception
indeed is resumable, and then issues the RESUME statement. The execution ofGET_TECH_ATTR is resumed right after the RAISE RESUMABLE EXCEPTION statement.
Hint:In this example, you can see very clearly the meaning of keeping the context ofthe exception. Without the BEFORE UNWIND addition, the system would deletethe newly created instance before executing the CATCH block. Resuming theGET_TECH_ATTR method and the constructor would not be possible.
Demonstration: How to Implement a Resumable Exception
Lesson: Implementing Advanced Exception Handling Techniques
© Copyright . All rights reserved. 431
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 444/505
Demonstrate SAPBC401_EXC_CATCH_D2. The purpose of this program is to raise andpropagate a resumable exception. Handle it, retaining the context and eventually resumeexecution right after the exception using the RESUME statement.
Implementation of Reraise Exceptions
Figure 164: Reraising an Existing Exception Object
There are two variants of RAISE EXCEPTION TYPE <exception_class>[EXPORTING ...] statement. This statement creates a new exception object, which is aninstance of class <exception_class>. Optionally, values can be provided for the constructorusing the EXPORTING addition.
The RAISE EXCEPTION <object_ref> statement uses an existing exception object, namely theone <object_ref> points to. This exception object was either created directly, using a CREATEOBJECT statement or, more commonly, was caught in a previous CATCH ... INTO ...statement and is to be passed on explicitly to the caller.
In the example, the constructor catches the exception CX_EXC raised by theGET_TECH_ATTR method. After some analysis of the exception object, maybe some clearingup, issuing a warning, and so on, the constructor decides to pass the exception on to the mainprogram. There it is handled again.
Demonstration: How to Reraise an Exception
Demonstrate SAPBC401_EXC_CATCH_D3. The purpose of this program is to handle anexception in middle method (constructor) and reraise it using RAISE EXCEPTION<object_ref>.
Unit 9: Object-Oriented Exception Handling
432 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 445/505
Mapping of Exceptions to Each Other
Figure 165: Mapping Exceptions to Each Other
In the example, the constructor catches the exception raised by the GET_TECH_ATTRmethod. After some analysis of the exception it raises a new exception of a different exceptionclass. It chains the existing exception object and the new one by passing a reference to the
existing object to the constructor of the new one. As a result, attribute PREVIOUS of the newexception object points to the exception object that preceded it.
The main program catches the second exception and gets access to the second exceptionobject. However, by using the public attribute PREVIOUS, it can navigate to the otherexception object and analyze it. In this way, it could access each instance in a chain ofexceptions and so follow the history of the raising of the exceptions in the call hierarchy.
Demonstration: How to Map an Exception to Another Exception
Demonstrate SAPBC401_EXC_CATCH_D4. The purpose of this program is to handle anexception in middle method that is the constructor, raise a new exception, and chain theexception objects via the PREVIOUS attribute.
Lesson: Implementing Advanced Exception Handling Techniques
© Copyright . All rights reserved. 433
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 446/505
Unit 9: Object-Oriented Exception Handling
434 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 447/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 448/505
3. Which other method signatures do you have to adjust to propagate the exception up tothe main program?
Task 3
In the main program, handle your new exception and evaluate the information of both, thenew and the original exception instance.
1. Catch your new exception in the main program wherever you create an instance of anairplane. Define a local reference variable for the purpose with a suitable type (suggestedname: GX_INV_VALUE).
2. Use this reference to extract the text of your new exception. Output the text on the list.
3. Use the same variables to export the text of the original exception. Output the text on thelist.
Unit 9: Object-Oriented Exception Handling
436 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 449/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 450/505
Hint:Check the signature of exception class CX_INVALID_VALUE to see if itcontains any attributes for which you need to provide values. Transfer thereference to the original exception instance to the exception instance that is
to be created.
a) See the source code extract from the model solution.
2. Adjust the signature of the constructor so that your new exception is propagated.
a) See the source code extract from the model solution.
3. Which other method signatures do you have to adjust to propagate the exception up tothe main program?
The constructors of LCL_CARGO_PLANE and LCL_PASSENGER_PLANE.
Task 3
In the main program, handle your new exception and evaluate the information of both, thenew and the original exception instance.
1. Catch your new exception in the main program wherever you create an instance of anairplane. Define a local reference variable for the purpose with a suitable type (suggestedname: GX_INV_VALUE).
a) See the source code extract from the model solution.
2. Use this reference to extract the text of your new exception. Output the text on the list.
a) See the source code extract from the model solution.
3. Use the same variables to export the text of the original exception. Output the text on thelist.
a) See the source code extract from the model solution.
Unit 9: Object-Oriented Exception Handling
438 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 451/505
LESSON SUMMARYYou should now be able to:
● Explain the hierarchy of predefined exception classes
● Explain different ways of handling an exception
● Retry after exceptions
● Implement resumable exceptions
● Reraise exceptions
● Map exceptions to each other
Lesson: Implementing Advanced Exception Handling Techniques
© Copyright . All rights reserved. 439
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 452/505
Unit 9: Object-Oriented Exception Handling
44 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 453/505
Unit 9
417Learning Assessment
1. Which of the following statement is used to raise class-based exceptions?
Choose the correct answer.
X A EXPORTING
X B RAISE EXCEPTION
X C CREATE OBJECT
X D CATCH
2. Which of the following block is used to catch and handle exceptions?
Choose the correct answer.
X A IMPORTING….RETURNING
X B METHOD…. ENDMETHOD
X C TRY … ENDTRY
X D TRY...CATCH...ENDTRY
3. An exception can only be handled if the statement that raised it is enclosed in a TRY-ENDTRY control structure.
Determine whether this statement is true or false.
X True
X False
4. TRY-ENDTRY structures can be nested to any depth.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 441
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 454/505
5. You can specify only two exception classes to the CATCH statement.
Determine whether this statement is true or false.
X True
X False
6. If an exception is raised, the name of the exception class is displayed in the __________field in debugging mode.
Choose the correct answer.
X A exception raised
X B last exception object
X C watchpoint
X D layout
7. Which of the following options can be selected when you create an exception class?
Choose the correct answer.
X A The exception class radio button
X B The with Message Class checkbox
X C The usual ABAP Class radio button
8. Which of the following is the step to define global exception classes?
Choose the correct answer.
X A Create a global class with the class type as exception class.
X B Define additional attributes.
X C Save as exception texts.
X D Activate the exception class.
Unit 9: Learning Assessment
442 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 455/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 456/505
13. Which of the following is used to jump back to the TRY statement?
Choose the correct answers.
X A RETRY
X B CATCH
X C TRY-ENTRY
X D RAISE
14. Which of the following is a prerequisite for using the RESUME statement?
Choose the correct answers.
X A The exception has to be caught.
X B The exception has to marked resumable.
X C The exception has to be propagated.
X D The exception has to be raised.
15. Which of the following statements raise a new exception object?
Choose the correct answers.
X A RAISE
X B RESUME
X C CATCH
Unit 9: Learning Assessment
444 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 457/505
Unit 9
421Learning Assessment- Answers
1. Which of the following statement is used to raise class-based exceptions?
Choose the correct answer.
X A EXPORTING
X B RAISE EXCEPTION
X C CREATE OBJECT
X D CATCH
2. Which of the following block is used to catch and handle exceptions?
Choose the correct answer.
X A IMPORTING….RETURNING
X B METHOD…. ENDMETHOD
X C TRY … ENDTRY
X D TRY...CATCH...ENDTRY
3. An exception can only be handled if the statement that raised it is enclosed in a TRY-ENDTRY control structure.
Determine whether this statement is true or false.
X True
X False
4. TRY-ENDTRY structures can be nested to any depth.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 445
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 458/505
5. You can specify only two exception classes to the CATCH statement.
Determine whether this statement is true or false.
X True
X False
6. If an exception is raised, the name of the exception class is displayed in the __________field in debugging mode.
Choose the correct answer.
X A exception raised
X B last exception object
X C watchpoint
X D layout
7. Which of the following options can be selected when you create an exception class?
Choose the correct answer.
X A The exception class radio button
X B The with Message Class checkbox
X C The usual ABAP Class radio button
8. Which of the following is the step to define global exception classes?
Choose the correct answer.
X A Create a global class with the class type as exception class.
X B Define additional attributes.
X C Save as exception texts.
X D Activate the exception class.
Unit 9: Learning Assessment- Answers
446 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 459/505
9. Which of the following syntax addition is used to propagate an exception from aprocedure?
Choose the correct answer.
X A CATCH
X B RAISING
X C METHODS
X D FORM
10. Which of the following blocks of code is executed before the CATCH block of the mainprogram after an exception has occurred?
Choose the correct answers.
X A CLEANUP
X B TRY
X C CATCH
X D RESUME
11. For subclasses of ____________ the corresponding exceptions cannot be propagatedexplicitly using the RAISING addition.
Choose the correct answer.
X A CX_STATIC_CHECK
X B CX_NO_CHECK
X C CX_DYNAMIC_CHECK
12. Which of the following is/are the way(s) to handle exception besides stopping theprogram?
Choose the correct answers.
X A Continue program
X B Remove the cause of error
X C Do not propagate an exception
X D Call method CX_SYSTEM_HANDLE
Unit 9: Learning Assessment- Answers
© Copyright . All rights reserved. 447
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 460/505
13. Which of the following is used to jump back to the TRY statement?
Choose the correct answers.
X A RETRY
X B CATCH
X C TRY-ENTRY
X D RAISE
14. Which of the following is a prerequisite for using the RESUME statement?
Choose the correct answers.
X A The exception has to be caught.
X B The exception has to marked resumable.
X C The exception has to be propagated.
X D The exception has to be raised.
15. Which of the following statements raise a new exception object?
Choose the correct answers.
X A RAISE
X B RESUME
X C CATCH
Unit 9: Learning Assessment- Answers
448 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 461/505
UNIT 10 Run Time Type Services
Lesson 1
Implementing Run Time Type Identification 450Exercise 25: Query Object Type Properties at Runtime 455
Lesson 2
Implementing Run Time Type Creation 458
UNIT OBJECTIVES
● Explain run time type indentification
● Query structure type properties at runtime
● Query object type properties at runtime
● Explain RTTC● Create a table type at runtime
© Copyright . All rights reserved. 449
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 462/505
Unit 10Lesson 1
426Implementing Run Time Type Identification
LESSON OVERVIEWThis lesson shows you how to implement run time type identification.
Business Example
An airline wants to identify all its cargo planes. For this reason, you require the followingknowledge:
● An understanding of run time type identification
● An understanding of how to query structure type properties at runtime
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain run time type indentification
● Query structure type properties at runtime
● Query object type properties at runtime
Run Time Type Identification
Figure 166: Dynamic Type Analysis with RTTI Classes
45 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 463/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 464/505
Query of Structure Type Properties at Using RTTI
Figure 168: RTTI – Querying Structure Attributes
In the following application example, you need to identify the attributes of a structure usingRTTI. You can use the subclass CL_ABAP_STRUCTDESCR for this purpose.
Since we need the attributes of a structure, we first define a reference to the appropriatedescription class. Instances of this class have a COMPONENTS attribute that you use todescribe the individual components of the relevant structure. This attribute is an internaltable. Therefore, you also need to define a work area with a compatible line type.
The functional method call provides the reference to the description instance for thestructure that you need to transfer (you could also generate the structure Work Areas (WA)dynamically, but in this example, it is static as usual).
The abstract class CL_ABAP_TYPEDESCR contains the static method DESCRIBE_BY_DATA.You can type its RETURNING parameter as a reference to this superclass. However, since youtyped the actual parameter GO_DESCR on the subclass CL_ABAP_STRUCTDESCR, you needto assign the object using a down-cast.
You can then access the attributes of the description instance in any form. In this example,the system displays the component names as column headers. (For the sake of clarity, wehave omitted the formatting options.)
Before the presentation, study carefully the static methods that the CL_ABAP_TYPEDESCRuses, and explain to the participants that they could call these methods using the subclassprefix too, since they are static methods. In the examples shown here, you could work witheither CL_ABAP_STRUCTDESCR or CL_ABAP_OBJECTDESCR. Ideally, this can also be usedas an additional check on the learning progress of the participants.
Demonstration: How to Query Structure Type Properties at Run Time
Unit 10: Run Time Type Services
452 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 465/505
If you have enough time, we recommend that you demonstrate extractsSAPBC401_DYND_RTTI_OBJECT, ideally to develop the source code together with theparticipants.
Query of Object Type Properties Using RTTI
Figure 169: RTTI – Querying Object-Type Attributes
As an example, we enhance the existing application with the travel agency and its businesspartner. In that simplified example, we had specified that an instance of the LCL_RENTALvehicle rental class reacts to an event by including the vehicle instance that triggered theevent in the separate MT_VEHICLES list. So far, the triggering instances could be buses(LCL_BUS) or trucks (LCL_TRUCK).
We will now extend this example. The vehicle rental company is now only interested in buses.
The SENDER parameter of the event handler method contains the reference to the triggeringvehicle instance. Its dynamic object type is to be analyzed to determine whether the vehicle inquestion is a bus or a truck.
A functional RTTI method call returns the reference to the description instance of thetransferred vehicle instance.
The abstract class CL_ABAP_TYPEDESCR has DESCRIBE_BY_OBJECT_ REF method. Youtype its returning parameter as a reference to this superclass. However, since you type theactual parameter R_DESCR on the subclass CL_ABAP_CLASSDESCR, you need to assign theobject using a down-cast.
You can then access the attributes of the description instance in any way. The functionalmethod GET_RELATIVE_NAME supplies the class name.
Lesson: Implementing Run Time Type Identification
© Copyright . All rights reserved. 453
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 466/505
Note:You could also fulfill the same purpose without using RTTI classes. For example,you could use a down-cast assignment from SENDER to a reference variable thathas a LCL_BUS static type. This would result in a runtime error for vehicle
instances that are not buses. The system could then catch this runtime error.Therefore, a runtime error not being triggered would be the criterion for includinga vehicle into the vehicle list.
Demonstration: How to Query Object Type Properties at Runtime
To demonstrate how to query object type properties at runtime, implement suitable part ofexercise Query Object Type Properties at Runtime.
Unit 10: Run Time Type Services
454 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 467/505
Unit 10Exercise 25
431Query Object Type Properties at Runtime
Business Example
In the program in question for the travel agency model, the airline (LCL_CARRIER) wants todetermine the highest cargo value of its cargo airplanes.
Template:
SAPBC401_RTT_T1
Solution:
SAPBC401_RTT_S1
Determine the highest cargo value for all cargo airplanes that you have entered in yourapplication. The cargo airplanes are present in the class LCL_CARRIER (of the airline).
1. If you have completed the optional exercise for a down-cast (determine the highest cargofor an airplane), you can complete your program ZBC401_##_MAIN (where ## is yourtwo-digit group number). Otherwise, copy the template program with all its components(suggested name for the new program: ZBC401_##_RTTI_1).
2. RTTI should now solve the method GET_HIGHEST_CARGO created in one of the earlierexercises for calculating the highest cargo value. Therefore, use RTTI instead of the TRY-
ENDTRY procedure. This specifically means that you now no longer need to catch theruntime error for a down-cast because you can determine the type of reference variable inadvance using an appropriate RTTI call.
© Copyright . All rights reserved. 455
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 468/505
Unit 10Solution 25
432Query Object Type Properties at Runtime
Business Example
In the program in question for the travel agency model, the airline (LCL_CARRIER) wants todetermine the highest cargo value of its cargo airplanes.
Template:
SAPBC401_RTT_T1
Solution:
SAPBC401_RTT_S1
Determine the highest cargo value for all cargo airplanes that you have entered in yourapplication. The cargo airplanes are present in the class LCL_CARRIER (of the airline).
1. If you have completed the optional exercise for a down-cast (determine the highest cargofor an airplane), you can complete your program ZBC401_##_MAIN (where ## is yourtwo-digit group number). Otherwise, copy the template program with all its components(suggested name for the new program: ZBC401_##_RTTI_1).
a) Copy the copy template in the usual manner or continue to work with your oldprogram.
2. RTTI should now solve the method GET_HIGHEST_CARGO created in one of the earlierexercises for calculating the highest cargo value. Therefore, use RTTI instead of the TRY-ENDTRY procedure. This specifically means that you now no longer need to catch theruntime error for a down-cast because you can determine the type of reference variable inadvance using an appropriate RTTI call.
a) See the source code extract from the model solution.
456 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 469/505
LESSON SUMMARYYou should now be able to:
● Explain run time type indentification
● Query structure type properties at runtime
● Query object type properties at runtime
Lesson: Implementing Run Time Type Identification
© Copyright . All rights reserved. 457
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 470/505
Unit 10Lesson 2
434Implementing Run Time Type Creation
LESSON OVERVIEWThis lesson explains the concepts of implementing Run Time Type Creation (RTTC).
As a developer, use the advanced exception handling techniques for catching the exceptions.For this reason, you require the following knowledge:
● An understanding of RTTC
● An understanding of creating a table type at runtime
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Explain RTTC
● Create a table type at runtime
Run Time Type Creation
Figure 170: RTTC – Dynamic Type Creation
For SAP Web AS 6.40, RTTC was added to the Run Time Type Information (RTTI) typeclasses to facilitate the creation of types at runtime.
The properties of the types are implemented by type-object attributes. This means that eachtype has a type object, whose attributes describe the properties of the type.
The class hierarchy of the type classes corresponds to the hierarchy of the types in the ABAPtype system. Type objects can be created by the type class methods. To obtain references to
458 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 471/505
type objects, you can call specific static methods for the class CL_ABAP_TYPEDESCR ormethods of the special type classes (GET_I, GET_C, ..., CREATE).
RTTC – Type Objects for the Type Description
Figure 171: RTTC – Type Objects for the Type Description
Features of type objects are as follows:● A type is defined completely by its type object.
● Every type has a runtime type object (RTTS instance).
● The runtime type object describes the data type completely.
● A type object is local to the program, transient, and anonymous.
● A type object cannot be deleted or changed.
Creation of a Table Type Using RTTC
Figure 172: RTTC – Creating a Table Type
Lesson: Implementing Run Time Type Creation
© Copyright . All rights reserved. 459
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 472/505
This topic is complex and some people who are new to the subject matter usually find itoverwhelming. So make sure that you refer to the relevant areas relating to RTTI and RTTC inthe documentation. This way the participants know that they can always refer to itthemselves at a later stage. In fact, it might be best to point out the documentation inadvance.
Also make sure that you clearly communicate in advance that this topic will not be coveredcompletely in this course. It is only an overview of the subject matter. Inform the participantsthat the complete topic will be covered in a separate course.
If you have enough time, you can run a demonstration for the participants and also carry outthe second optional exercise. Dynamically creating data objects at runtime is a new area formany participants and the second exercise will impress the participants with the optionsavailable with ABAP Objects. If you have a tight schedule then you can discuss theoreticallythe new RTTS features for SAP NetWeaver 6.40.
With the CREATE method, the CL_ABAP_TABLEDESCR class enables you to create a localtable type at runtime. The P_LINE_TYPE parameter is an important formal parameter of thestatic method. The P_LINE_TYPE parameter describes the line type using a reference to theCL_ABAP_STRUCTDESCR. In the example provided, SPFLI table name is used as the linetype. For example, the DESCRIBE_BY_NAME method instantiates a suitable object. TheABAP_TRUE parameter from the sample program originates from a type pool that is usedinternally in the RTTC classes.
The question that now arises is what you should technically do with the table type that hasbeen created. For instance, you could use the table type as an example of creating an internaltable at runtime. The program block used for creating an internal table at runtime is asfollows:
...DATA gt_itab TYPE REF TO DATA,
go_table_Type TYPE REF TO cl_abap_tabledescr.
...
* Creation of internal tabletype with static method
* CREATE of RTTS-class cl_abap_tabledescr
...
CREATE DATA gt_itab TYPE HANDLE go_table_Type.
Using the HANDLE addition, the CREATE DATA statement in the example creates an internaltable, whose type is described by an RTTS type object. A reference variable from the statictype of the CL_ABAP_TABLEDESCR class that refers to a type object is specified for theHANDLE. The type object may have been created on the existing data objects using the RTTSmethods or by dynamically defining a new data type.
LESSON SUMMARYYou should now be able to:
● Explain RTTC
● Create a table type at runtime
Unit 10: Run Time Type Services
46 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 473/505
Unit 10
437Learning Assessment
1. Which subclass is used to identify the attributes of a structure using Run Time TypeIdentification?
Choose the correct answer.
X A CL_ABAP_TYPEDESCR
X B CL_ABAP_STRUCTDESCR
X C CL_ABAP_OBJECTDESCR
X D CL_ABAP_CLASSDESCR
2. Which attribute is used to describe the individual components of any relevant structure?
Choose the correct answer.
X A COMPONENTS
X B TYPE_KIND
X C LENGTH
X D DECIMALS
3. Which parameter contains the reference to the triggering vehicle instance of the eventhandler method?
Choose the correct answer.
X A Returning
X B Actual
X C Sender
X D Interface
© Copyright . All rights reserved. 461
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 474/505
4. Which of the following are features of type objects?
Choose the correct answers.
X A Every type has a runtime type object.
X B Runtime type object describes the data type.
X C A type object can be deleted or changed.
X D A type is defined completely by its type object.
5. Which of the following is used to create an internal table of Run Time Type Services typeobject?
Choose the correct answer.
X A HANDLE
X B CREATE DATA
X C DATA
Unit 10: Learning Assessment
462 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 475/505
Unit 10
439Learning Assessment- Answers
1. Which subclass is used to identify the attributes of a structure using Run Time TypeIdentification?
Choose the correct answer.
X A CL_ABAP_TYPEDESCR
X B CL_ABAP_STRUCTDESCR
X C CL_ABAP_OBJECTDESCR
X D CL_ABAP_CLASSDESCR
2. Which attribute is used to describe the individual components of any relevant structure?
Choose the correct answer.
X A COMPONENTS
X B TYPE_KIND
X C LENGTH
X D DECIMALS
3. Which parameter contains the reference to the triggering vehicle instance of the eventhandler method?
Choose the correct answer.
X A Returning
X B Actual
X C Sender
X D Interface
© Copyright . All rights reserved. 463
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 476/505
4. Which of the following are features of type objects?
Choose the correct answers.
X A Every type has a runtime type object.
X B Runtime type object describes the data type.
X C A type object can be deleted or changed.
X D A type is defined completely by its type object.
5. Which of the following is used to create an internal table of Run Time Type Services typeobject?
Choose the correct answer.
X A HANDLE
X B CREATE DATA
X C DATA
Unit 10: Learning Assessment- Answers
464 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 477/505
UNIT 11 Advanced ABAP Object-Oriented Techniques
Lesson 1
Explaining Advanced ABAP Object-Oriented Techniques 466
UNIT OBJECTIVES● Explain shared objects
● Explain ABAP Unit tests
© Copyright . All rights reserved. 465
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 478/505
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 479/505
Shared Objects Classes
Figure 173: Shared Objects – Basics
Give a very brief overview of the SAP NetWeaver 6.40 features of ABAP Unit and sharedobjects.Refer the participants to the relevant specialized course. The participants need toabsorb all of the new knowledge they have gained during the first week of the course and youdo not want to overwhelm them with more new information.
As of SAP NetWeaver 6.40, you can buffer data across project using shared objects.
Potential uses of shared objects are as follows:● Storing a shopping basket
The shopper fills the basket, which is then read by the salesperson later.
● Storing a catalog
Many users access the data at the same time.
Before the introduction of shared objects, ABAP programs could only access the memoryarea using the EXPORT and IMPORT statements with the additions SHARED BUFFER orSHARED MEMORY. Instances of classes existed only in the internal mode of an ABAPprogram. With the introduction of shared objects, the shared memory was extended toinclude the shared objects memory, in which shared objects can be stored.
Note:In general, the objects stored in the shared objects memory are instances ofclasses. However, as of SAP NetWeaver 7.0 it is also possible to store dynamicallycreated data objects in the shared objects memory.
Prerequisites for shared objects are as follows:
Lesson: Explaining Advanced ABAP Object-Oriented Techniques
© Copyright . All rights reserved. 467
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 480/505
● Cross-program buffering of data with a small number of write accesses but a large numberof read accesses (recommendation – between once a day and once each hour).
● Simultaneous read accesses are supported.
● Access is regulated by a lock mechanism.
● Data objects that are referenced using data references cannot be stored directly.
● Memory bottlenecks result in runtime errors and have to be caught.
Shared objects are stored in areas of the shared memory. You create and manage areas andtheir attributes in transaction SHMA. A prerequisite for storing an object in the shared memoryis that the class of the object must be defined with the addition SHARED MEMORY ENABLEDof the CLASS statement. For global classes, the shared memory enabled attribute must beselected in the Class Builder.
Shared Objects – Areas and Handles
Figure 174: Shared Objects – Areas and Handles
Each area is linked with a global area root class, whose attributes may contain its own data
and references to other shared memory-enabled classes. An area is a template for areainstances in the shared memory. Several area instances with different names can be createdfor one area.
When you define an area with transaction code SHMA, a global and final area class with thesame name is created for the area as a subclass of CL_SHM_AREA.
In an ABAP program, an area is accessed exclusively using the methods of the generated areaclass. There are static methods for attaching an ABAP program or its internal mode to areainstances in the shared memory which is called as attach methods.
Unit 11: Advanced ABAP Object-Oriented Techniques
468 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 481/505
Shared Objects – Example I
Figure 175: Shared Objects – Example I
With attachment, an instance of the area class is generated as an area handle and a lock is setat the same time. The ABAP program can use the area handle to access the attached areainstance versions and thus also the shared objects stored there. The area handle alsocontains the methods for releasing the attachment or the lock which is called as detachmethods.
Lesson: Explaining Advanced ABAP Object-Oriented Techniques
© Copyright . All rights reserved. 469
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 482/505
Shared Objects – Example II
Figure 176: Shared Objects – Example II
Note:For more details and information, refer to the SAP Library or attend the relevant
ABAP course for advanced developers.
Demonstration: How to Implement Shared Objects
To demonstrate shared objects you can use shared memory area CL_SHM_AREA_HANDLEwith programs SAPBC401_PVW_SHMA_WRITE and SAPBC401_PVW_SHMA_READ. Todemonstrate the programs proceed as follows:
. Run the transaction code SHMA, enter the name of the shared objects in the Area Namefield.
2. Explain some of the properties of the shared memory area.
3. In transaction SHMA, choose the Monitor pushbutton and demonstrate that the sharedmemory area is not yet active.
4. In a different window, display and explain program SAPBC401_PVW_SHMA_WRITE.Debug the program step by step. After each statement or method call, show the changesin the Shared Objects Monitor in your other window.
5. Display and explain program SAPBC401_PVW_SHMA_READ. Debug it step-by-step.After each statement or method call, show the changes in the other window.
Unit 11: Advanced ABAP Object-Oriented Techniques
47 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 483/505
ABAP Unit Tests
Figure 177: Overview of ABAP Unit
As of SAP NetWeaver AS 6.40, you can create test classes with the ABAP Unit tool.
ABAP Unit tool is a test tool integrated into the ABAP runtime environment, which is used to
check the functionality of the code units of a program that is module tests.Individual tests are implemented in various ABAP programs as test methods of local testclasses. The tests of several ABAP programs can be grouped together in test items.
The tests are programmed in ABAP objects as follows.● The test function is contained in the test methods of test classes.
● These test classes are contained locally in the program that is to be tested. This meansthat there are no transport or versioning problems.
● If an error occurs, the rest of the test procedure can be controlled.
● The test code is not created in the production environment and it is therefore not executedthere; so there is no loss of execution speed for normal coding in the productionenvironment.
To be able to test a class and its methods using ABAP Unit, test classes need to be created.They are contained locally in the program to be tested. A test class is defined with the additionFOR TESTING of the CLASS statement. The following example shows a test class that teststhe functionality of the method get_attributes.
Lesson: Explaining Advanced ABAP Object-Oriented Techniques
© Copyright . All rights reserved. 471
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 484/505
ABAP Unit with the Example of the Method get_attributes
Figure 178: ABAP Unit with the example of the method get_attributes
Test methods are defined and implemented in the test class. To some degree, the test classesand test methods form the frame for the calls of the methods to be tested. Therefore, the testmethods themselves do not need to be tested. As is typical in these test methods, instances
of the classes to be tested are created and their methods are then called and checked.
Test methods have no parameters. They are declared with the addition FOR TESTING of theMETHODS statement. Every test method corresponds to an ABAP unit test. In a test method,the test coding is implemented by calling certain parts of the program under certain startconditions and checking and logging results and statuses by using the methods of the systemclass CL_AUNIT_ASSERT.
The definition of test classes divides a program into production coding and test coding. Thetest coding of test classes is not generated in production systems. Access from theproduction coding to a test class is not possible.
Unit 11: Advanced ABAP Object-Oriented Techniques
472 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 485/505
ABAP Unit Test Example
Figure 179: ABAP Unit Test Calls
Note:
For more information and details, refer to the SAP Library.
Demonstration: How to Implement ABAP Unit Tests
If there is still enough time, the demo program SAPBC401_PVW_UNIT_D1 is also available.Ensure that you make yourself familiar with the individual parts of the program in advanceand consider in detail how you will proceed.
In most courses the participants will be exhausted by the long week at this point, and they willnot show much enthusiasm for a new topic. A general idea of the basic principles of ABAPUnit will therefore be perfectly sufficient.
LESSON SUMMARYYou should now be able to:
● Explain shared objects
● Explain ABAP Unit tests
Lesson: Explaining Advanced ABAP Object-Oriented Techniques
© Copyright . All rights reserved. 473
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 486/505
Unit 11: Advanced ABAP Object-Oriented Techniques
474 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 487/505
Unit 11
451Learning Assessment
1. Which of the following are the prerequisite for shared objects?
Choose the correct answers.
X A Cross-program buffering of data
X B Simultaneous read accesses are not supported
X C Memory bottlenecks result in runtime errors and have to be caught
2. Test methods are not defined and implemented in the test class.
Determine whether this statement is true or false.
X True
X False
© Copyright . All rights reserved. 475
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 488/505
Unit 11
452Learning Assessment- Answers
1. Which of the following are the prerequisite for shared objects?
Choose the correct answers.
X A Cross-program buffering of data
X B Simultaneous read accesses are not supported
X C Memory bottlenecks result in runtime errors and have to be caught
2. Test methods are not defined and implemented in the test class.
Determine whether this statement is true or false.
X True
X False
476 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 489/505
UNIT 12 Case Study
Lesson 1
Developing Object-Oriented Case Study 478Exercise 26: Create an UML Class Diagram 483Exercise 27: Create an UML Class Diagram 487
UNIT OBJECTIVES
● Develop object-oriented case study
© Copyright . All rights reserved. 477
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 490/505
Unit 12Lesson 1
454Developing Object-Oriented Case Study
LESSON OVERVIEWThis lesson provides with an object-oriented case study.
You must first develop a program for this case study at least once yourself so that you canestimate how much programming is required and answer any questions the participants mayask.
Caution:If requested by the participants, the section can also be moved to the end ofthe course but avoid spending all of the last day on the exercise becausesome participants may be critical of this approach and may complain thatthey learned nothing on the last day.
The first two times this course was taught, the instructors omitted the case study entirelyand devoted more time to the exercises in the course.
Business Example
You want to get a rough overview of some advanced techniques of object-orientedprogramming with ABAP. For this reason, you require the following knowledge:
● An understanding of UML diagram
● An understanding of object-oriented program
LESSON OBJECTIVESAfter completing this lesson, you will be able to:
● Develop object-oriented case study
478 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 491/505
Requirements of an Object-Oriented Case Study
Figure 180: Case Study – Requirements I
The ABAP Objects program to be created should provide the user for example, the travelagent with a screen containing functions for managing customers using flight waiting lists. Itshould be possible to maintain a waiting list for each flight row from table SFLIGHT with thekey CARRID, CONNID, and FLDATE.
Note:The model shown here is one possible solution to the waiting list requirementsdescribed. The course participants are free to use their own UML class diagram,which will produce a different solution.
All waiting lists are to be stored in a waiting list buffer called WAIT_LIST which is technically aninternal table. In addition to the flight data, the waiting lists are to contain a list of allcustomers who have registered for this flight. The functions of this application are shown inthe figure.
Lesson: Developing Object-Oriented Case Study
© Copyright . All rights reserved. 479
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 492/505
Case Study – Requirements II
Figure 181: Case Study – Requirements II
The screen and functions shown are to be created in accordance with the requirementspecifications. The screen layout and flow logic are already available. You now have toimplement the actual flow, that is, the intelligence of the program using object-oriented
techniques.Functions of Pushbuttons
The individual buttons are to have the following functions:
Pushbutton Functions
Display Displays the waiting list for the specifiedflight (CARRID, CONNID,FLDATE)
Create Creates the waiting list for the specified flight(CARRID, CONNID, FLDATE)
Delete Deletes the waiting list for the specified flight(CARRID, CONNID, FLDATE)
Add Adds the customer selected on the right ofthe screen to the flight waiting list selectedon the left
Delete (Customer) Deletes the customer selected on the right ofthe screen from the flight displayed on theleft
Position Displays the selected customer’s position onthe waiting list
Unit 12: Case Study
48 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 493/505
Pushbutton Functions
Customer Type (optional) Shows whether the selected customer is aprivate customer or a business customer(you will find the relevant information in theCUSTTYPE field of table SCUSTOM)
Display customers Moved Up (optional) Displays all customers from the list who weresuccessfully moved up from the waiting listto get a seat on the flight
Status Log (optional) Displays the number of customers from thelist who were successful in getting a seat on aflight
Lesson: Developing Object-Oriented Case Study
© Copyright . All rights reserved. 481
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 494/505
Unit 12: Case Study
482 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 495/505
Unit 12Exercise 26
457Create an UML Class Diagram
Business Example
A travel agency wants to offer its customers an additional service. If customers want to booka flight that is already fully booked, they can have their names put on a waiting list for thisflight. If a seat becomes free at a later date, a customer from the waiting list can be placed onthe flight. This customer’s name is then removed from the waiting list.
You can use the following suggestions but you can also choose a model of your own, whichyou can then use for an alternate implementation later. If you do not wish to do this, follow theinstructions below to create a class diagram.
1. The waiting list should be the central class in the model. Use LCL_WAITLIST as the classname (ZCL_##_WAITLIST if you are using the Class Builder).
The class should have the public attributes CARRID, CONNID, FLDATE, and the privateattribute CUSTOMER_LIST.
The following public methods should be defined in the UML:
CONSTRUCTOR, ADD, DELETE, GET_POS, GET_FIRST and GET_WAIT_LIST.
Hint:
It would actually be more in line with the encapsulation concept to define allof the attributes here as private and then access these attributes of thewaiting list with external methods. We suggest that you define the attributesas public to save time and effort, but this is your choice.
2. Customers form another class. Use LCL_CUSTOMER as the class name(ZCL_##_CUSTOMER if you are using the Class Builder).
This class should have the public attribute ID and the private attributes NAME, STREET,CITY, and APP_DATE.
The following public methods should be defined in the UML:
CONSTRUCTOR and GET_ATTRIBUTES.3. As a straightforward solution, you could simply define the buffer for the waiting lists in the
main program as a normal internal table. However, you want to use one class in this caseand therefore the singleton concept is used.
Define the buffer for the waiting lists as singleton class LCL_BUFFER (ZCL_##_BUFFER ifyou are using the Class Builder).
The class should have the attribute BUFFER_LIST: the private, static attributeN_O_ENTRIES, and a private, static reference to itself.
The following public methods should be defined in the UML:
CLASS_CONSTRUCTOR (as a static method) and DISPLAY_N_O_ENTRIES.
© Copyright . All rights reserved. 483
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 496/505
Hint:It would actually be more in line with the encapsulation concept to define theBUFFER_LIST attribute as private in this case and then access this attributewith methods from the main program. In this case, we suggest that you
define this attribute as public and then access it externally and directly tosave time and effort, but this is your choice.
If you follow the model solution for the class diagram, you must use methods.
4. Define the relationships between these classes and assign the cardinalities (multiplicity).
You also have the option of mapping the navigation options.
Unit 12: Case Study
484 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 497/505
Unit 12Solution 26
459Create an UML Class Diagram
Business Example
A travel agency wants to offer its customers an additional service. If customers want to booka flight that is already fully booked, they can have their names put on a waiting list for thisflight. If a seat becomes free at a later date, a customer from the waiting list can be placed onthe flight. This customer’s name is then removed from the waiting list.
You can use the following suggestions but you can also choose a model of your own, whichyou can then use for an alternate implementation later. If you do not wish to do this, follow theinstructions below to create a class diagram.
1. The waiting list should be the central class in the model. Use LCL_WAITLIST as the classname (ZCL_##_WAITLIST if you are using the Class Builder).
The class should have the public attributes CARRID, CONNID, FLDATE, and the privateattribute CUSTOMER_LIST.
The following public methods should be defined in the UML:
CONSTRUCTOR, ADD, DELETE, GET_POS, GET_FIRST and GET_WAIT_LIST.
Hint:
It would actually be more in line with the encapsulation concept to define allof the attributes here as private and then access these attributes of thewaiting list with external methods. We suggest that you define the attributesas public to save time and effort, but this is your choice.
a) Refer to the model solution.
2. Customers form another class. Use LCL_CUSTOMER as the class name(ZCL_##_CUSTOMER if you are using the Class Builder).
This class should have the public attribute ID and the private attributes NAME, STREET,CITY, and APP_DATE.
The following public methods should be defined in the UML:CONSTRUCTOR and GET_ATTRIBUTES.
a) See the model solution.
3. As a straightforward solution, you could simply define the buffer for the waiting lists in themain program as a normal internal table. However, you want to use one class in this caseand therefore the singleton concept is used.
Define the buffer for the waiting lists as singleton class LCL_BUFFER (ZCL_##_BUFFER ifyou are using the Class Builder).
The class should have the attribute BUFFER_LIST: the private, static attributeN_O_ENTRIES, and a private, static reference to itself.
The following public methods should be defined in the UML:
© Copyright . All rights reserved. 485
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 498/505
CLASS_CONSTRUCTOR (as a static method) and DISPLAY_N_O_ENTRIES.
Hint:It would actually be more in line with the encapsulation concept to define theBUFFER_LIST attribute as private in this case and then access this attribute
with methods from the main program. In this case, we suggest that youdefine this attribute as public and then access it externally and directly tosave time and effort, but this is your choice.
If you follow the model solution for the class diagram, you must use methods.
a) See the model solution.
4. Define the relationships between these classes and assign the cardinalities (multiplicity).
You also have the option of mapping the navigation options.
a) See the model solution.
Figure 182: Waiting List – UML Class Diagram
Unit 12: Case Study
486 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 499/505
Unit 12Exercise 27
461Create an UML Class Diagram
Business Example
A customer wants to book a flight through a travel agency but the flight is already fullybooked. However, the customer is offered the option of registering for the waiting list for thisflight.
Convert the definitions from your class diagram into a program. If you want to use thesuggestions proposed in this unit, follow the instructions below. If you have created your ownalternate UML class diagram, you can ignore these instructions.
1. Use program SAPBC401_PRJT_WAITLIST as a template. Your program should be calledZBC401_##_PRJS_WAITLIST.
Copy all Include programs from the template and rename them. You should always usethe target names specified with your group number (suggested name:ZBC401_##_PRJS_INC_xxx).
2. The copied template already contains the parameters for the application to be created.Familiarize yourself with the program structure. This program contains a screen on whichbuttons for all of the required functions are already provided. However, with the exceptionof the icons in the standard toolbar, these functions still have to be implemented.
For the meaning of the individual buttons, refer to the screen shown in the figure and theexplanatory text in your course notes.
Note:If you have no experience with dynamic screens or dialog programming withABAP, speak to your course instructor.
Hint:The display of the customer data on the waiting list function code SHOW is
not part of this exercise. Therefore, to save time, you can use functionmodule BC401_DISPLAY_DATA. Later, when you are implementing thisfunction, you should familiarize yourself with its interface and use it fordisplay. If you have enough time, you can also use the ABAP List Viewer(ALV) Grid Control.
Note:To simplify the scenario, avoid persistent storage of the waiting list. In otherwords, the data is not to be saved to the database.
© Copyright . All rights reserved. 487
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 500/505
Note:The focus of this exercise is on the creation of a viable model for which theexisting components should be examined. The main point of the exercise is notto implement the program in detail.
Unit 12: Case Study
488 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 501/505
Unit 12Solution 27
463Create an UML Class Diagram
Business Example
A customer wants to book a flight through a travel agency but the flight is already fullybooked. However, the customer is offered the option of registering for the waiting list for thisflight.
Convert the definitions from your class diagram into a program. If you want to use thesuggestions proposed in this unit, follow the instructions below. If you have created your ownalternate UML class diagram, you can ignore these instructions.
1. Use program SAPBC401_PRJT_WAITLIST as a template. Your program should be calledZBC401_##_PRJS_WAITLIST.
Copy all Include programs from the template and rename them. You should always usethe target names specified with your group number (suggested name:ZBC401_##_PRJS_INC_xxx).
a) Carry out this step in the usual manner.
2. The copied template already contains the parameters for the application to be created.Familiarize yourself with the program structure. This program contains a screen on whichbuttons for all of the required functions are already provided. However, with the exceptionof the icons in the standard toolbar, these functions still have to be implemented.
For the meaning of the individual buttons, refer to the screen shown in the figure and theexplanatory text in your course notes.
Note:If you have no experience with dynamic screens or dialog programming withABAP, speak to your course instructor.
Hint:
The display of the customer data on the waiting list function code SHOW isnot part of this exercise. Therefore, to save time, you can use functionmodule BC401_DISPLAY_DATA. Later, when you are implementing thisfunction, you should familiarize yourself with its interface and use it fordisplay. If you have enough time, you can also use the ABAP List Viewer(ALV) Grid Control.
Note:To simplify the scenario, avoid persistent storage of the waiting list. In otherwords, the data is not to be saved to the database.
© Copyright . All rights reserved. 489
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 502/505
Note:The focus of this exercise is on the creation of a viable model for which theexisting components should be examined. The main point of the exercise is notto implement the program in detail.
a) The model solution provided here encapsulates the buffer with the waiting lists in classLCL_BUFFER. The waiting lists in the buffer can be accessed with public methods.
It is also possible to create the buffer in the main program directly as a non-encapsulated internal table. Due to time restrictions, this is recommended, but thedecision is up to you.
Unit 12: Case Study
49 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 503/505
LESSON SUMMARYYou should now be able to:
● Develop object-oriented case study
Lesson: Developing Object-Oriented Case Study
© Copyright . All rights reserved. 491
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 504/505
Unit 12: Case Study
492 © Copyright . All rights reserved.
8/15/2019 BC401 ILT 10 InstructorHandbook A4 Batchid 9444 ExplanationTexts
http://slidepdf.com/reader/full/bc401-ilt-10-instructorhandbook-a4-batchid-9444-explanationtexts 505/505
Unit 12
467Learning Assessment
1. Which of the following pushbutton is used to display the number of customers from thelist who were successful in getting a seat on a flight?
Choose the correct answer.
X A Position
X B Status
X C Delete
X D Customer Type