SAP NetWeaver Programming – ABAP Objects Dylan Liu 劉兆宏 SAP NetWeaver Technical Consultant Email&MSN: dylan.sap@gmail.com Oct. 6 2008 SAP NetWeaver Programming – ABAP Objects ABAP Objects: Overview Definition ABAP - Advanced Business Application Programming - Is a historically grown 4GL language - Is specialized for business applications ABAP Objects - Object-oriented extension of ABAP programming language History ABAP Programming Model ABAP supports a hybrid programming model: • A object-oriented programming model that is based on classes and interface of ABAP objects • A procedural programming model that is based on procedural calls and system event handling • Both models are interoperable – you can call classes from classic procedures, and you can call classic procedures from methods. SAP NetWeaver Programming – ABAP Objects ABAP Objects: Concept Object-oriented Programming Abstraction - Ability to reflect real-world processes - real-world modeled in classes and mapped in objects Encapsulation - Implementation details are hidden behind interfaces. - Ensure that the abstract representation of an object is used only in accordance with its specification. Inheritance - Abstractions derived from existing ones. Instantiation - Enables you to create multiple instances of a class. Why use ABAP Objects? • ABAP Objects results in a clean and secure programming style. • SAP delivers essential APIs (ex. Control Framework) in object-oriented wrapped classes. • Most SAP new products are written in ABAP Objects! Object-oriented Programming Basics • Class is the model or the template • Object is an instance of class • Local class is created within any ABAP program and only visible there • Global class is created with the Class Builder tool and visible in any ABAP program SAP NetWeaver Programming – ABAP Objects ABAP Objects: Keywords and Syntax Define a CLASS CLASS class_name DEFINITION. .... ENDCLASS. CLASS class_name IMPLEMENTATION. .... ENDCLASS. Visibility Section Public - All components are public and can be addressed by all subclasses, the class itself and other external classes. Protected - Components of this section are protected and can only be addressed by the class itself and the subclasses Private - Can only be used in the methods of the class itself Define Visibility Section CLASS class_name DEFINITION. PUBLIC SECTION. .... PROTECTED SECTION. .... PRIVATE SECTION. .... ENDCLASS. Controlling the Instantiation Public instantiation - Allow to any user to create objects (default) Protected instantiation - Allow the creation of objects in methods of subclasses Private instantiation - Only the class itself can create objects Define Instantiation CLASS class_name DEFINITION CREATE PUBLIC | PROTECTED | PRIVATE. ENDCLASS. Components Components of a class 1. Attributes 2. Methods 3. Events Components – Attribute - The data objects within a class - All data types of the ABAP type hierarchy can be used - ‘DATA’ statement is used for instance attributes - ‘CLASS-DATA’ for static attribute Define Attributes CLASS attributes DEFINITION. PRIVATE SECTION. DATA objectValue TYPE i. CLASS-DATA objectCount TYPE i. ENDCLASS. Components – Methods - Processing block with a parameter interface - Local data - Instance method can access all attributes and events - Static method can access only static attributes and events Define Instance Methods CLASS class_name DEFINITION. PUBIC SECTION. METHODS meth IMPORTING .. Ii TYPE type EXPORTING .. Ei TYPE type .. CHANGING .. Ci TYPE type .. EXCETPIONS .. Ei ENDCLASS. Define Static Methods CLASS class_name DEFINITION. PUBIC SECTION. CLASS-METHODS class_meth IMPORTING .. Ii TYPE type EXPORTING .. Ei TYPE type .. CHANGING .. Ci TYPE type .. EXCETPIONS .. Ei ENDCLASS. Implementation of Methods CLASS class_name DEFINITION. METHOD meth. … ENDMETHOD. ENDECLASS. Components – Methods Two special methods constructor - implicitly called for each instantiation of a new object - Execute by runtime environment. class_constructor – first time a class is accessed Destructors ABAP Objects does not provide any destructors for application development. Define Object Reference Variables To create and access an object, object references in reference variables are needed. Syntax: DATA ref TYPE REF TO class Instantiating Syntax: CREATE OBJECT ref. Different Selectors Accessing fields of a structure – Structure component selector “-” Accessing object components – Object component selector “->” – Class component selector “=>” – Interface component selector “~” Use of Methods Call instance method: Syntax: CALL METHOD oref->get_data. Call class method: Syntax: CALL METHOD class=>get_data. Functional Method Functional method Method with any number of input parameters but only one return value. It can be used in operand positions for functions and expressions. Use of Functional Method Functional method used in expressions: Syntax IF obj->functional_method( ) = abap_true. …… do some thing ENDIF. Method Call CALL METHOD oref->get_data. CALL METHOD class=>get_data. CALL METHOD oref->get_data IMPORTING P1 = P1 RECEIVING P2 = P2. Method Call Short Form - Functional Method Call Style oref->get_data( ). class=>get_data( ). P2 = oref->get_data( P1 ). Special Reference Variables The self-reference: me The superclass-reference(used in method call): super CLASS DEFINITION DEFERRED CLASS - DEFERRED, LOAD Syntax CLASS class DEFINITION DEFERRED | LOAD . CLASS DEFINITION DEFERRED CLASS c1 DEFINITION DEFERRED. CLASS c2 DEFINITION. PUBLIC SECTION. DATA c1ref TYPE REF TO c1. ENDCLASS. CLASS c1 DEFINITION. PUBLIC SECTION. DATA c2ref TYPE REF TO c2. ENDCLASS. CLASS cl_gui_cfw DEFINITION LOAD. DATA state LIKE cl_gui_cfw=>system_state. Components – Events - Allow the objects of a class to publish its status. Other objects can then respond to the change in status. 1. Event trigger does not know the event handler. 2. Event trigger therefore does not initially know if the event will even have an effect. - Publish and Subscribe mechanism, i.e. Broadcasting Event Triggers and Event Handlers Trigger1 Raise Event Trigger2 Raise Event Handler1 Handler1 Terms Events Each method can trigger the events of its class Handler methods Methods can be declared as handler methods for events Registering handlers Objects for an event can be registered at runtime as handlers for the objects of the classes which can trigger the event Define Events CLASS raising_class DEFINITION. PUBLIC SECTION. EVENTS: raised_event. ENDCLASS. Raise Events CLASS raising_class IMPLEMENTATION. METHOD raising_method. RAISE EVENT raised_event. ENDMETHOD. ENDCLASS. Define Handler Methods CLASS handler_class DEFINITION. PUBLIC SECTION. METHODS: handler_method FOR EVENT raised_event OF raising_class. ENDCLASS. Handler Methods CLASS handler_class IMPLEMENTATION. METHOD handler_method. … some logics here ENDMETHOD. ENDCLASS. Register Handlers SET HANDLER handler_instance->handler_method FOR ALL INSTANCES. SET HANDLER handler_instance->handler_method FOR handled_instance. SAP NetWeaver Programming – ABAP Objects ABAP Objects: Exception Handling Exception Handling Exceptions are events that arise during the execution of an ABAP program at which the program is interrupted, because it is not possible to continue processing the program in a meaningful way. Exceptions are either treatable or untreatable. Exception Handling Runtime Errors Exceptions Before Release 6.10 Class-Based Exceptions Runtime Errors Exception that was not handled data RESULT type I. RESULT = 1 / 0. Runtime Errors Shortdump screenshot Exceptions Before Release 6.10 Handling exceptions as catchable runtime errors data RESULT type I. catch system-exceptions ARITHMETIC_ERRORS = 4. RESULT = 1 / 0. endcatch. if SY-SUBRC = 4. ... endif. Class-Based Exceptions Handling exceptions using/with exception classes data MYREF type ref to CX_SY_ARITHMETIC_ERROR. data ERR_TEXT type STRING. data RESULT type I. try. RESULT = 1 / 0. catch cx_sy_arithmetic_error into MYREF. ERR_TEXT = MYREF->GET_TEXT( ). endtry. Defining Exceptions All exception classes must inherit from the common superclass CX_ROOT and one of its subordinate classes: · · · CX_STATIC_CHECK CX_DYNAMIC_CHECK CX_NO_CHECK Propagating Exceptions The RAISING addition is specified in the declaration of a method / subroutine: METHODS meth ... RAISING cx_... cx_... FORM form ... RAISING cx_... cx_... SAP NetWeaver Programming – ABAP Objects Use of ABAP Objects: Advanced Concept Advanced Concept of Object-oriented Programming Inheritance Interface Friend Inheritance Superclass Generalization Animal dog cat Subclass Specialization Visibility in Inheritance Public - contains all the public components of all superclasses and its own added public components. Protected - Contains all the protected components of all superclasses as well as its own. Private - Contains its own private components. Address by its own methods. Method Redefinition Re-implement the method of supper class In Class declaration part: Syntax: METHODS meth REDEFINITION. Up Cast Up Cast (Also referred to as widening cast) - Assignment between reference variables, where the static type of the target variables is similar or identical to the static type of the source variables. Casting operator = or MOVE ... TO … . Down Cast Down Cast (Also called a narrowing cast) - an assignment between reference variables in which the static type of the target variable more specific than the static type of the source variable. Casting operator ?= or MOVE ... ?TO … . Abstract Classes and Methods When needed a class model for subclasses and do not require any objects from this class. Abstract Class Syntax: CLASS class DEFINITION ABSTRACT. … ENDCLASS Abstract Method CLASS class DEFINITION ABSTRACT. PUBLIC SECTION. METHODS: method ABSTRACT. ENDCLASS. Final Classes and Methods When needed to protect a class or individual method from uncontrolled specialization Final Class Syntax: CLASS class DEFINITION FINAL. … ENDCLASS Final Method Syntax: CLASS class DEFINITION FINAL. PUBLIC SECTION. METHODS: method FINAL. ENDCLASS Constructors in Inheritance Must always take the definition of the superclasses into account METHOD constructor. CALL METHOD super->constructor. ENDMETHOD. Interface - Describes the public visibility section of a given class without itself implementing functionality. - Are defined either locally or globally in the class library. Define Interface INTERFACE intf. DATA … CLASS-DATA .. METHODS … CLASS-METHODS … EVENTS … CLASS-EVENTS… ENDINTERFACE. Implement Interfaces in Classes CLASS class DEFINITION. PUBLIC SECTION. … INTERFACES: intf1, intf2 … … ENDCLASS. Interfaces are incorporated solely in the public visibility section of a class. Interface Implementation in Classes Class must implement all the methods of all incorporated interfaces in its implementation part. CLASS class IMPLEMENTATION. … METHOD intf1~ method… … ENDMETHOD. ENDCLASS. Composing Interfaces INTERFACE intf1. METHODS meth. ENDINTERFACE. INTERFACE intf2. INTERFACES intf1. METHODS meth. ENDINTERFACE. Composing Interfaces CLASS class DEFINITION. PUBLIC SECTION. INTERFACES intf2. ENDCLASS. CLASS class IMPLEMENTATION. METHOD intf1~meth. … ENDMETHOD. METHOD intf2~meth….. ENDMETHOD. ENDCLASS. Alias Names for Interface Component Syntax CLASS class DEFINITION. PUBLIC SECTION. INTERFACES intf. ALIASES name FOR intf~comp. … ENDCLASS. Alias Names for Interface Component Example: CALL METHOD oref~intf->method. = CALL METHOD oref->alias. Friend The additions FRIENDS of statement CLASS define other classes or interfaces as friends of the class and thus grant them access to their protected and private components. Friend The additions FRIENDS of statement CLASS define other classes or interfaces as friends of the class and thus grant them access to their protected and private components. Friend - Example INTERFACE i1. … ENDINTERFACE. CLASS c1 DEFINITION CREATE PRIVATE FRIENDS i1. PRIVATE SECTION. DATA a1 TYPE c LENGTH 10 VALUE 'Class 1'. ENDCLASS. CLASS c2 DEFINITION. PUBLIC SECTION. INTERFACES i1. METHODS m2. ENDCLASS. Friend - Example CLASS c2 IMPLEMENTATION. METHOD m2. DATA oref TYPE REF TO c1. CREATE OBJECT oref. WRITE oref->a1. ENDMETHOD. ENDCLASS. SAP NetWeaver Programming – ABAP Objects ABAP Objects: ABAP Workbench Tool Class Builder Global class is created with the Class Builder tool and visible in any ABAP program. Class Builder is a special maintenance tool in ABAP Workbench Class Builder TCode: SE24 / SE80 SAP NetWeaver Programming – ABAP Objects Use of ABAP Objects: OO Transaction OO Transactions In transaction maintenance (SE93), you can specify a transaction code as an OO transaction. OO Transactions OO Transactions SAP NetWeaver Programming – ABAP Objects ABAP Objects for Java Programmer Similarities Between Java and ABAP Like Java, • ABAP is a programming language • ABAP is object-oriented • ABAP runs on a virtual machine • ABAP is the foundation for a whole technology Similarities - Typical Java Development Tool Similarities – ABAP Development Tool Similarities - Classes Syntactical differences aside, ABAP supports classes as Java does In ABAP, the declaration and implementation of a class are split into separate parts Similarities - Classes Syntactical differences aside, ABAP supports attributes and methods as Java does (apart from method name overloading) In ABAP, a class has three visibility sections (PUBLIC, PROTECTED, PRIVATE) Similarities – Method Implementations For basic operations, syntax can be translated almost one to one • ”->” (or ”-”) replaces ”.”, ”.” replaces ”;”, ”me” replaces ”this” • In ABAP, blocks are built by keywords instead of {} • Raising exceptions follows the same principles Similarities – Exceptions and Inheritance Exception classes must be derived from predefined superclasses The superclasses define how exception handling is checked Similarities – Handling Objects in Java Similarities – Handling Objects in ABAP Similarities – Keywords 1 Similarities – Keywords 2 SAP NetWeaver Programming – ABAP Objects Use of ABAP Objects: The Control Framework The Control Framework (CFW) In the SAP system, you can use ABAP to control desktop applications (custom controls). The application logic runs on the SAP application server, which drives the custom control at the frontend. The Control Framework supports controls (ActiveX and JavaBeans) that are implemented within the SAP GUI. CFW – HTML Control CFW – Picture Control CFW – ALV Grid Control Control Framework Architecture Global class in the class library for each GUI control supplied and that when working with GUI controls, for each control object on the frontend there is a proxy object of the corresponding class in the ABAP programs. Control Framework Architecture ABAP programming works only with the proxy objects The CFW forwards its method calls to actual GUI control objects and informs the objects of the ABAP program by triggering events about the user actions on the GUI controls. Control Framework Architecture Control Framework Example Container Controls CL_GUI_CUSTOMER_CONTAINER CL_GUI_DOCKING_CONTAINER CL_GUI_SPLITTER_CONTAINER CL_GUI_DIALOGBOX_CONTAINER Application Controls CL_GUI_TOOLBAR CL_GUI_PICTURE CL_GUI_HTML_VIEWER CL_GUI_TEXTEDIT CL_GUI_SIMPLE_TREE CL_GUI_ALV_GRID Enjoy Demo Center TCode: DWDM SAP NetWeaver Programming – ABAP Objects Use of ABAP Objects: BAdIs Enhancement using Business Add-Ins Business Add-Ins (BAdIs) are one of the most important technologies used to adapt SAP software to specific requirements. Business Add-Ins: Architecture Implementation of Business Add-Ins SAP NetWeaver Programming – ABAP Objects Use of ABAP Objects: Web Programming Web Programming • BSP • Web Dynpro for ABAP • Custom HTTP Handler Class • … SAP Netweaver Programming ABAP Q&A Copyright 2008 SAP AG. All Rights Reserved No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are registered trademarks of Microsoft Corporation. IBM®, DB2®, DB2 Universal Database, OS/2®, Parallel Sysplex®, MVS/ESA, AIX®, S/390®, AS/400®, OS/390®, OS/400®, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere®, Netfinity®, Tivoli®, Informix and Informix® Dynamic ServerTM are trademarks of IBM Corporation in USA and/or other countries. ORACLE® UNIX®, is a registered trademark of ORACLE Corporation. X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group. Citrix®, the Citrix logo, ICA®, Program Neighborhood®, MetaFrame®, WinFrame®, VideoFrame®, MultiWin® and other Citrix product names referenced herein are trademarks of Citrix Systems, Inc. HTML, DHTML, XML, XHTML 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. MarketSet SAP, and Enterprise Buyer are jointly owned trademarks of SAP AG and Commerce One. R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves information purposes only. National product specifications may vary.