ABAP Objects Overview

Embed Size (px)

DESCRIPTION

ABAP Objects Overview

Citation preview

  • ABAP Objects - Overview

    Table of Contents

    ABAP Objects - Overview Object Orientation, 1 Definition of Classes and Interfaces, 2 Classes, 3 .. Components of Classes, 3.1 .... Visibility Sections in Classes, 3.1.1 .... Attributes, 3.1.2 .... Methods, 3.1.3 ...... Interface Parameters in Methods, 3.1.3.1 ...... The C Destructor, 3.1.3.2 ...... Kernel Methods, 3.1.3.3 .... Constructors, 3.1.4 ...... Visibility of Instance Constructors, 3.1.4.1 .... Events, 3.1.5 .... Data Types and Constants, 3.1.6 Inheritance, 4 .. Redefining Methods, 4.1 .. Abstract and Final Methods and Classes, 4.2 .. Inheritance and Polymorphism, 4.3 .. Inheritance and Interfaces, 4.4 .. Inheritance and Visibility, 4.5 .. Inheritance and the Component Namespace, 4.6 .. Inheritance and Static Components, 4.7 .. Inheritance and Constructors, 4.8 .. Inheritance and Instantiation, 4.9 .. Inheritance and Events, 4.10 Interfaces, 5 .. Nesting Interfaces, 5.1 Events, 6 Friends - Friendship Between Classes, 7 Objects, 8 .. Object References, 8.1 .. Accessing Class Components, 8.2 .. Object References in Internal Tables, 8.3 .. Weak References, 8.4 Statements in ABAP Objects, 9 .. Statements for Defining Classes and Interfaces, 9.1 .. Statements for implementing methods, 9.2 .. Statements in Class and Interface Pools, 9.3 .. ABAP Objects - Keywords, 9.4 .. Replacements for Obsolete Language Constructs in ABAP Objects, 9.5 Examples for ABAP Objects, 10 .. ABAP Objects, Overview, 10.1 .. ABAP Objects, Classes, 10.2 .. ABAP Objects, Inheritance, 10.3 .. ABAP Objects, Interfaces, 10.4 .. ABAP Objects, Events, 10.5 .. ABAP Objects, OO Transaction, 10.6

    ABAP Objects - Overview

    ABAP Objects is the object-oriented extension of the ABAP language.

    ABAP Objects adds a complete set of language elements to ABAP that allow object-oriented programming. This object-oriented extension of ABAP builds on the previous range of languages, and is fully compatible with them.

    Page 1 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • ABAP Objects can be used in existing programs, and the statements that can be used in ABAP Objects correspond to practically all of the remaining SAP language scope. However, specific obsolete language elements are not permitted in conjunction with ABAP objects due to a clean up of the ABAP language.

    ABAP Objects supports:

    Classes

    Interfaces

    Objects

    Object References

    Inheritance

    Note

    Package SABAP_DEMOS_CAR_RENTAL contains a complete sample application written in ABAP Objects. Its presentation layer is implemented using a Web Dynpro or screen. The Web Dynpro calls interface methods that are implemented in a class and that, in turn, access classes that implement database accesses.

    1 Object Orientation

    Object orientation (or, more correctly, object-oriented programming) is a problem-solving method that represents the real world in a series of software objects.

    Object-oriented programming is based on a progamming model in which data and functions are unified in objects. The remaining language scope of ABAP mainly supports procedural programming, where the data is stored at other places than the objects and where programs that are modularized by procedures access this data.

    This document defines a few general terms that are widely used in object orientation and in ABAP Objects.

    Objects

    Objects represent abstract or concrete objects of the real world. An object is a section of program code that has data (called attributes) and provides services called methods (sometimes also known as operations or functions). Methods typically work with private data in the object (attributes, also known as the object state), that are only visible within the object. This guarantees the internal consistency of the object, since the data is only changed by the methods, not by the user. This ensures that the object is consistent in itself.

    Classes

    Classes are program code that describes objects. Technically, an object is an instance of a class. In theory, you can create an infinite number of objects from a single class definition. Each instance of a class (object) has its own values for its attributes.

    Object References

    In a program, you identify and address objects using a unique object reference. They allow you to access the attributes and methods of an object.

    In object-oriented programming, objects usually have the following characteristics:

    Encapsulation

    Objects restrict the external visibility of their resources (attributes and methods). Each object has an interface that determines how other objects or applications can use it. The implementation of the object is encapsulated (not visible outside the class).

    Page 2 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • Polymorphism

    Methods with the same name can behave differently in different classes. In object-oriented programming, you can use interfaces to address methods with the same name in different objects. The form of address always remains the same, but the actual method implementation is class-specific, and can be different in each class.

    Inheritance

    You can derive a class from another class. A derived class (subclass) inherits the data and methods of its superclass. You can add new methods to a subclass, or redefine existing methods. Redefined methods have the same name and interface as the original method. Their classes are therefore polymorphous, too.

    Benefits of Object Orientation

    Object orientation has the following advantages:

    Complex software systems become easier to understand, since an object-oriented architecture resembles reality more closely than other programming techniques.

    Changes in object-oriented systems should be possible locally (at class level), without further changes being necessary in other parts of the system. This reduces the amount of maintenance required.

    Polymorphism and inheritance enable many individual components to be reused.

    Object-oriented systems require fewer revisions and less maintenance, because the majority of problems can be discovered and corrected in the design and development phases.

    Achieving these goals requires:

    Object-oriented programming languages Object-oriented programming techniques do not necessarily require object-oriented programming languages. However, they do depend on the implementation of object-oriented constructions in the system kernel.

    Object-oriented tools Object-oriented tools help you create object-oriented programs in object-oriented languages. They allow you to store and visualize your program objects and the relationship between them.

    Object-oriented modeling Object-oriented modeling of a software system is the most important, most time consuming, and most difficult task required to achieve the above goals. Object-oriented design encompasses more than just object-oriented programming, and offers logical advantages that are independent of the eventual implementation.

    2 Definition of Classes and Interfaces

    Classes and interfaces in ABAP Objects can be declared either globally or locally.

    You define global classes and interfaces with the Class Builder in ABAP Workbench. They are stored centrally in the class library in the repository. From a technical perspective, global classes and interfaces are defined in class pools or interface pools. All ABAP programs in an AS ABAP can access these global classes and interfaces. Access is managed by the package check. Global classes and interfaces are stored in a namespace along with the data types of ABAP Dictionary.

    You can define local classes and interfaces in all programs except interface pools and type groups. They can be used statically only in the defining program. Dynamic access from other programs is possible but not advisable. When you use a class in an ABAP program, the system first searches for a local class with the specified name. If it does not find one, it then looks for a global class. Otherwise, there is no difference

    Page 3 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • between using global and local classes or interfaces.

    If you are defining a local class that is only used in a single program, it is usually sufficient to define the outwardly visible components so that it fits into that program. Conversely, each global class is available throughout the system, which means that its public interface can only be specified with reference to data types that are themselves visible throughout the system.

    The syntax for defining classes and interfaces is essentially the same for local and global classes and interfaces. The only difference is in the PUBLIC addition, which makes a distinction between the global classes and interfaces and local declarations.

    Global classes and interfaces can be edited in the Class Builder, either in form-based or source-code based mode. In form-based mode, the Class Builder generates the relevant source code that can be accessed directly in source-code based mode.

    Defining Classes

    Classes consist of ABAP source code, enclosed in the ABAP statements CLASS ... ENDCLASS. A complete class definition consists of a declaration part and, if required, an implementation part.

    The declaration part of a class named class consists of a statement block:

    CLASS class DEFINITION. ... ENDCLASS.

    It contains the declaration for all components (attributes, methods, events) of the class. All the components of a class must be assigned explicitly to a visibility section (PUBLIC SECTION, PROTECTED SECTION, PRIVATE SECTION), which defines from where each component can be accessed. When you define local classes, the declaration part belongs to the global program data. You should therefore place it at the beginning of the program.

    If you declare methods in the declaration part of a class, you must also write an implementation part for it. This consists of a further statement block:

    CLASS class IMPLEMENTATION. ... ENDCLASS.

    The implementation part of a class contains the implementation of all methods of the class. Methods are procedures, that is, processing blocks of an ABAP program. The position of the implementation part in the source code is thus unimportant. For clarity, however, you should either put all the implementation parts of local classes at the end of the program, or directly after the relevant definition part. If you do the latter, note that you must then assign subsequent non-declarative statements explicitly to a processing block such as START-OF-SELECTION, so that they can be accessed.

    Defining Interfaces

    The definition of an intf interface is enclosed in the statements:

    INTERFACE intf. ... ENDINTERFACE.

    The The definition contains the declaration for all components (attributes, methods, events) of the interface. In interfaces, you can define the same components as in classes. You cannot assign the components of an interface explicitly to a visibility section, because interface components always extend the public area of a class when they are implemented in it. Interfaces do not have an implementation part, since their methods are implemented in the class that implements the interface.

    3 Classes

    Page 4 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • The type of an object is known as its class. A class is an abstract representation, or, metaphorically speaking, a set of instructions for building objects. So that you can describe the properties of objects, classes contain components, which define the state and behavior of objects.

    Global and Local Classes

    You can define classes globally in the class library in the repository or locally in an ABAP program.

    Global classes are coded in a special ABAP program, a Class-Pool, whereas local classes can be coded in almost every ABAP program. Global classes are visible in all ABAP programs. The usablity depends on the package check. Local classes can only be used statically in their own program. Dynamic accesses are also possible across program limits but it is not recommended. When a global class is used for the first time, the class pool is loaded into the internal session of the user. The local classes of a class pool can be used by the pool's global classes.

    Except for the storage type and the visibility, there are hardly any conceptual differences between global and local classes. One of the few differences is that in the public interface of a global class only references to public types are possible. These types are subdivided into global and local friends.

    In principle, it also does not make any difference if you call a method of a local or global class. This is the reason why classes that are used by several programs are exclusively created in the class library. You should avoid, if possible, to reuse local classes using include programs.

    3.1 Components of Classes

    The content of a class is composed of components. The components define the attributes of objects of a class. Each component is declared in the definition of the class in one of the four visibility sections that the interfaces define externally. Within a class, all its components are visible. All components are in the same namespace, which means that the names of all components in a class must be different.

    The individual components are:

    Attributes

    Methods

    Events

    Types and constants

    SAP makes a distinction between components of this type that are available on an instance-dependent basis for every object, and instance-independent components that are only available once in a class. The instance-dependent components are called instance components; the instance-independent components are known as static components.

    In ABAP objects, classes can define the components listed above. Since all components that can be declared in classes can also be declared in interfaces, this description also applies to interfaces.

    The components of classes can be accessed internally, and depending on the visibility, also from outside the class. If they are accessed externally, component selectors must be used for addressing.

    3.1.1 Visibility Sections in Classes

    The declaration section of a class can be split into up to four different visibility sections.

    These sections define the external visibility of the class components and therefore the interfaces of the class for all users allowed by the package concept. Each component of a class must be explicitly assigned to one of the visibility sections. Only the friends of a class ignore the associated restrictions.

    Public visibility section All components declared in the public visibility section defined with PUBLIC SECTION are accessible to all

    Page 5 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • users as well as in the methods of all inheritors and the class itself. The public components of the class form the interface between the class and its users.

    Protected visibility section All components declared in the protected visibility section defined with PROTECTED SECTION are accessible

    in the methods of all inheritors and in the class itself. Protected components form a special interface between a class and its subclasses.

    Private visibility section All components declared in the private visibility section defined with PRIVATE SECTION are only accessible in the class itself, and are also not visible to the inheritors. The private components therefore do not form an interface to the users of the class.

    The following table summarizes the visibilities of a class:

    Note

    A subclass can generally never access the protected components of a subclass from a different branch in the inheritance hierarchy, even if they are inherited from a common superclass. This rule can only be lifted by a friendship.

    Encapsulation

    The three visibility sections form the basis for the important feature of encapsulation in ABAP Objects. When declaring a class, you should ensure you declare the minimum possible number of components in the public section and create these public components carefully. The public components of global classes may not be changed once you have released the class.

    Programming Guideline

    Exploit the benefits of encapsulation

    Note

    The class is the smallest encapsulation unit in ABAP Objects. A method can therefore use all components of all instances of the same class, except for the components of its own class. An exception to this rule are subclasses that cannot access the private components of superclasses, if they are not their friends.

    Example

    In method m1 of class c1, reference variables of static type c1 can be used to access the protected attribute a11 and the private attribute a12 of any objects of c1. In method m2 of subclass c2, a reference variable of static type c2 can similarly be used to access the protected attribute a11. Access to the attribute using a reference variable of static typec1 is not permitted, as it would otherwise also be possible to change an attribute of an object of the superclass or another subclass. It is not possible to access the private attribute of the superclass with either reference variable.

    CLASS c1 DEFINITION. PUBLIC SECTION. METHODS m1. PROTECTED SECTION. DATA a11 TYPE i. PRIVATE SECTION. DATA a12 TYPE i.

    Visible for PUBLIC SECTION PROTECTED SECTION PRIVATE SECTION

    Same class and its friends X X X

    Any subclasses X X -

    Any repository objects X - -

    Page 6 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • ENDCLASS. CLASS c1 IMPLEMENTATION. METHOD m1. DATA lref1 TYPE REF TO c1. lref1->a11 = 0. "OK lref1->a12 = 0. "OK ENDMETHOD. ENDCLASS. CLASS c2 DEFINITION INHERITING FROM c1. PUBLIC SECTION. METHODS m2. ENDCLASS. CLASS c2 IMPLEMENTATION. METHOD m2. DATA: lref1 TYPE REF TO c1, lref2 TYPE REF TO c2. lref1->a11 = 0. "Syntax warning, access to a11 not permitted lref2->a11 = 0. "OK "lref1->a12 = 0. "Syntax error, access to a11 not permitted "lref2->a12 = 0. "Syntax error, a12 not visible ENDMETHOD. ENDCLASS.

    3.1.2 Attributes

    Attributes are data objects of any ABAP data type that are internal to a class. The content of the attributes specifies the status of the object. You can also define reference variables, which you can then use to create and address objects. This allows objects to be accessed within classes.

    Attributes are defined in the declaration part of a class. Public attributes are completely visible from outside the class and are therefore part of the interface between objects and their users. To encapsulate the status of the object, you need to use protected, package-visible, or private attributes. You can also restrict the changeability of non-private attributes using the READ-ONLY addition during the declaration.

    Instance Attributes

    The content of instance attributes forms the instance-dependent status of the object. Instance attributes are declared using the DATA statement. You cannot use the COMMON PART addition in classes.

    Static Attributes

    The content of static attributes forms the instance-independent status of the object, which is valid for all instances of the class. Static attributes are available once for each class. They are declared using the CLASS-DATA statement and are retained throughout the entire runtime. All the objects within a class can access its static attributes. Changes to a static attribute in an object are visible to all other objects within that class.

    Data Types of Attributes

    The data types of all attributes, including instance attributes and in particular bound data types, belong to the static properties of a class. Therefore, in a LIKE addition, you can use the class component selector or reference variables to refer to the visible attributes of a class without first creating an object. In this way, you can access the properties of the public static attributes of global classes from every program.

    Page 7 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • Example

    Reference to the data type of an instance attribute attr of a global class cl_global.

    DATA dref TYPE REF TO cl_global. DATA: f1 LIKE cl_global=>attr,

    f2 LIKE dref->attr.

    Boxed Components

    Attributes declared as structures can be declared as static boxes using the BOXED addition, like substructures of nested structures. With static boxes, initial value sharing results in reduced memory requirement for infrequently used structures of regularly used objects. As a boxed component, a static box is a deep component administered using an internal reference, like strings and internal tables.

    3.1.3 Methods

    Methods are internal procedures of a class that determine the behavior of an object. They can access all the attributes of all instances of their class and can therefore change the status of an object. Methods have a parameter interface, used by the system to pass values to them when they are called, and by which they can return values to the caller. The private attributes of a class can only be changed using methods of the same class.

    A method meth is declared in the declaration section of a class and is implemented in the implementation part of the class using the processing block

    METHOD meth. ... ENDMETHOD.

    As in all procedures, local data types and data objects can be declared in methods. Methods are called statically using the expression meth( ... ) or dynamically using the statement CALL METHOD (Dynamic Invoke).

    Instance Methods

    Instance methods are declared using the METHODS statement. They can access all the attributes of a class and can trigger all its events.

    Static Methods

    Static methods are declared using the CLASS-METHODS statement. This statement can access static attributes of a class and is can trigger static events only.

    Constructors

    As well as the normal methods that are called explicitly, there are two special methods called constructor and class_constructor, which are called automatically when an object is created or when a class component is accessed for the first time.

    Functional Methods

    Functional methods are methods with any number of IMPORTING parameters and one RETURNING parameter. Functional methods cannot just be called as standalone statements, but also as functional method calls in operand positions for functions and expressions. Here they can be also be combined as method chainings.

    3.1.3.1 Interface Parameters in Methods Interface parameters in methods are input parameters (IMPORTING, CHANGING parameters) and output parameters (EXPORTING, CHANGING, RETURNING parameters). In declarations with the statements

    Page 8 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • METHODS

    CLASS-METHODS

    EVENTS

    CLASS-EVENTS

    the following attributes are determined:

    Passing parameters by reference or by value

    With the exception of the return value (RETURNING parameters), parameters can be passed both by value or reference. Passing by reference is standard with methods. If only a name p is specified in the parameter declaration, the parameter is passed implicitly as a reference. If a VALUE(p) is specified instead, then the parameter is passed as a value. The return value may only be passed as a value. Passing by reference can also be explicitly specified with other parameters using REFERENCE(p). An IMPORTING parameter transferred by reference, cannot be changed in the method.

    Typing parameters All parameters must be typed during declaration using the addition TYPE or the addition LIKE. The following entries are allowed after TYPE as parameter types:

    Optional parameters All input parameters (IMPORTING, CHANGING parameters) can be defined in the declaration as optional parameters using the additions OPTIONAL or DEFAULT. These parameters must not necessarily be transfered when the method

    is called. With the addition OPTIONAL your parameter remains initialized according to type, while the addition DEFAULT allows you to enter a start value.

    3.1.3.2 The C Destructor

    A destructor is a special method that is called automatically when an object is deleted. Destructors can be used to release resources used by the object that are not included in garbage collection. ABAP Objects do not currently have a destructor in which a regular ABAP processing block can be programmed.

    For special cases and for internal use only, the predefined instance method destructor can be declared in the public visibility section of a class:

    CLASS class DEFINITION. PUBLIC SECTION. METHODS destructor [NOT AT END OF MODE]. ... ENDCLASS.

    In the implementation of the method destructor only one statement can currently be used:

    CLASS class IMPLEMENTATION. METHOD destructor. SYSTEM-CALL c-destructor 'name' USING attr. ENDMETHOD. ENDCLASS.

    This means that the destructor makes it possible to call a C routine name when an object is deleted. The routine must exist in the ABAP kernel to ensure that no syntax errors occur.

    When the optional addition NOT AT END OF MODE is used, the destructor is not executed if the internal session is closed anyway. A destructor is usually also executed at the end of a session and should mainly be used to release external resources that are not released automatically when the session is closed.

    Page 9 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • When the C routine is called, attributes attr1, attr2, and so on, of the class of any complex data type can be passed on to the routine. If multiple parameters are to be passed, an appropriate data type must be defined.

    During the lifetime of an internal session, the time at which the method destructor is executed depends on when the garbage collector is started. When an internal session is closed, the destructors that are not declared with the addition NOT AT END OF MODE are executed for all objects. In the case of inheritance, the destructors of subclasses are executed before the destructors of superclasses.

    3.1.3.3 Kernel Methods

    For internal use, kernel methods can be implemented in the ABAP kernel instead of in the ABAP language.

    Introduction

    Kernel methods allow you to directly call ABAP kernel functions implemented in C or C++. Kernel methods replace the previous concepts of C calls and system calls. No new C calls or system calls need to be introduced.

    Kernel methods offer the same checks and security features as normal ABAP methods. Except for the Constructors and the C Destructor, all ABAP methods can be implemented as kernel methods. An ABAP method can still be redefined as a kernel method and a kernel method can still be redefined as an ABAP method within a path of the inheritance hierarchy.

    For C developers who want to implement a kernel method, an API is available that allows simple, high-performance, and secure access to arguments. Class-based exceptions also continue to be supported.

    Defining Kernel Methods

    Declaration in ABAP

    A kernel method is declared in the same way as a normal ABAP method, in Class Builder or in the declaration section of a local class. Whether a method is implemented as a kernel method is not important for the declaration. In ABAP, this means that a kernel method can be used just like a normal ABAP method.

    Implementation in ABAP

    A method is specified as a kernel method in the implementation part of the class using the optional addition BY KERNEL MODULE kmod1 kmod2 ... of the statement METHOD. kmod1, kmod2, ... are the names of kernel modules that implement the method. The ABAP implementation of a kernel method must be empty, which means that there cannot be any ABAP statements between METHOD and ENDMETHOD:

    METHOD meth BY KERNEL MODULE kmod1 kmod2 ... ENDMETHOD.

    Constructors and the C Destructor cannot be implemented as kernel methods. There is a separate mechanism for the C Destructor.

    After KERNEL MODULE, you can specify a list of kernel modules kmod1, kmod2, ... Currently, you can only specify C functions of the kernel for kmod1, kmod2, ... The list after KERNEL MODULE is evaluated by the compiler from left to right. The first kernel module in the list that is registered in the kernel (see below) is used in the generation.

    If no valid kernel module is found in the list, a syntax error occurs. There are still two standard C functions that can appear at the end of the list: FAIL and IGNORE. If one of these functions is specified at the end of the list, then a syntax error is avoided if the previous list does not contain a valid module. IGNORE is used to ignore the call of a kernel method of this type (behavior as in an empty ABAP implementation) and, in the case of FAIL, a handleable exception of the class CX_SY_DYN_CALL_ILLEGAL_METHOD is raised.

    Examples

    METHOD meth BY KERNEL MODULE xx_impl_630 xx_impl_620 xx_impl_610.

    Page 10 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • First, the kernel is searched for xx_impl_630. The kernel is then searched for nach xx_impl_620, and finally for xx_impl_610. If none of these functions are found, a syntax error is raised.

    METHOD meth BY KERNEL MODULE xx_impl_630 xx_impl_620 FAIL.

    First, the kernel is searched for xx_impl_630. Then the kernel is searched for xx_impl_620. If neither of these functions are found, a syntax error is not raised; a handleable exception of the class CX_SY_DYN_CALL_ILLEGAL_METHOD is raised instead, when the method is called.

    METHOD meth BY KERNEL MODULE xx_impl_620 xx_impl_610 IGNORE.

    First, the kernel is searched for xx_impl_620. Then the kernel is searched for xx_impl_610. If none of the functions are found, a syntax error is not raised; the empty ABAP implementation is called instead, when the method is called.

    Implementation in the Kernel

    Currently, only C functions can be used as kernel modules of kernel methods. The C functions can have any position in the kernel. No special includes from the ABAP runtime environment are required for implementing the C function. The C functions must have a specific interface. The interface itself is wrapped by a macro called ARGUMENTS. All required definitions and prototypes are in the include //src/include/abkmeth.h. This is the only include needed for defining C functions for kernel methods.

    Since C functions can be defined in C and C++ , you must use externC in C++:

    #include "abkmeth.h" ... externC void name_of_cmodule( ARGUMENTS ) { ...

    }

    A C function that implements a kernel method must be registered for the kernel method. If, after METHOD meth BY KERNEL MODULE, you specify the name of a C function that was not registered for the kernel method, a syntax error occurs (as mentioned above). You can register several C functions for a kernel method. The sequence of the kernel modules kmod1, kmod2, ... specified in the list after METHOD meth BY KERNEL MODULE defines which of the registered C functions is used. This allows downward-compatible further development of kernel methods.

    To make changes to the registration active, you must recompile the destination lib of the project krn/runt and relink the kernel.

    Registration

    C functions are registered in the signature file //src/krn/runt/abkmeth.sig using the following syntax for kernel methods (all ABAP IDs must be specified in uppercase letters):

    KERNEL_METHOD("CLASS","METH", cfunc,argcnt)

    This definition registers the C function cfunc for the kernel method meth of a global class class. The C function expects a number of argcnt arguments.

    Kernel methods of local classes in class pools or other ABAP programs are registered using the following macros:

    KERNEL_METHOD_CLASS_LOCAL("GCLASS","CLASS","METH",cmodule,argcnt)

    KERNEL_METHOD_PROGRAM_LOCAL("PROG","CLASS","METH",cmodule,argcnt)

    The technique is the same as with KERNEL_METHOD, except that you must specify the global class gclass for local classes in class pools and the program prog for program-local classes.

    Registering Arguments

    Page 11 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • All ABAP data objects (such as parameters, attributes, or global data) that are to be accessed in C functions for kernel methods, are treated as arguments of the C function.

    The argument list of a C function for a kernel method is not limited to the interface parameters of the ABAP method and does not have to contain these completely. Before you access arguments within C functions for kernel methods, these arguments must be registered.

    The argcnt arguments must be registered immediately after the C function is registered using KERNEL_METHOD. A single argument is defined (registered) using one of the following macros:

    ARGUMENT_basetype(index,"name",type_kind,"type",read_write)

    ARGUMENT_[C|N|X](index,"name",type_kind,"type",read_write,length)

    ARGUMENT_P(index,"name",type_kind,"type",read_write,length,decimals)

    ARGUMENT_STRUCT(index,"name",type_kind,"type",read_write,ctype)

    These macros define an argument with the name name and an index index.

    You must use basetype to assign the type of the ABAP data object according to the following table. If the basetype is C, N, X, P, or STRUCT, you must specify more parameters than for other types.

    basetype ABAP Data Type Type in C

    C c with specified length SAP_CHAR (*) [Length]

    C_GENERIC c without specified length SAP_CHAR*

    X x with specified length SAP_RAW (*) [Length]

    X_GENERIC x without specified length SAP_RAW*

    N n with specified length SAP_CHAR (*) [Length]

    N_GENERIC n without specified length SAP_CHAR*

    P p with specified length and decimals SAP_BCD (*) [Length]

    P_GENERIC p without specified length and decimals SAP_BCD*

    D d SAP_DATE*

    T t SAP_TIME*

    INT1 b SAP_INT1*

    INT2 s SAP_SHORT*

    I i SAP_INT*

    F f SAP_DOUBLE*

    DECFLOAT16 decfloat16 DecFloat16

    DECFLOAT34 decfloat34 DecFloat34

    STRING string StrRef*

    XSTRING xstring StrRef*

    TABLE All table types TABH_REF*

    OBJ_REF All object references ObjRef*

    DATA_REF All data references FldRef*

    STRUCT All structure types Registered type ctype*

    ANY any void*

    DATA data void*

    SIMPLE simple void*

    CSEQUENCE csequence void*

    XSEQUENCE xsequence void*

    NUMERIC numeric void*

    CLIKE clike SAP_CHAR*

    Page 12 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • The macro parameters have the following meanings:

    name is the ID for any ABAP data object in uppercase letters that could also be used in an ABAP implementation of the kernel method. In particular, the ID can contain links with component selectors, for example me->attr or struc-comp.

    index is a sequential number from 1 to argcnt. The arguments are accessed using this index.

    For type_kind you can specify either TYPE or TYPE_REF_TO.

    type is the ID for any ABAP data type in uppercase letters that could also be used in an ABAP implementation of the kernel method. type_kind and type are used to check the interface of the kernel

    method in ABAP.

    For read_write you can specify either READ or WRITE. This defines whether you have read or write access to the argument and is evaluated in the access macros.

    length is used to specify the length of all ABAP data types with a generic length for ARGUMENT_[C|N|X|P]. In characters for c and n and in bytes for x and p.

    For ARGUMENT_P you use decimals to specify the number of decimal places.

    For ARGUMENT_STRUCT you use ctype to specify a suitable C type. This type should be generated from an ABAP type definition using saphfile.

    Accessing Arguments

    After registering the arguments, you can use the following macros to access them within the C function. With the exception of the direct access to the data control block, the access macros do not require any includes from the ABAP runtime environment.

    ARGUMENT_basetype_READ(index,"name");

    This macro returns the read address of an argument with the type const ctype, where ctype is defined by basetype according to the above table. The index and name of the argument must be passed. You must specify additional parameters for the generic types (see below). You only need the index to access the argument. However, to make the C function more legible and ensure that additional consistency checks can be executed, you must also specify the name. If the kernel is compiled in debugging mode, the system executes a consistency check between index and name; the specified C type and ABAP type of the argument are also checked. In the case of an error, an appropriate ABAP runtime error is triggered (KMETH_INVALID_ARGUMENT_ID, KMETH_INVALID_ARGUMENT_NAME, or KMETH_INVALID_CTYPE_LENG). No checks are made in the optimized kernel.

    ARGUMENT_basetype_WRITE(index,"name");

    This macro has the same semantics as ARGUMENT_basetype_READ. However, the system returns the write address. The system also checks whether the argument was defined as a write argument. If you try to write access a read-only argument (for example, a constant), this triggers the ABAP runtime error KMETH_ARGUMENT_READ_ONLY.

    ARGUMENT_[C|N]_READ(index,"name",lengthU); ARGUMENT_[C|N]_WRITE(index,"name",lengthU); ARGUMENT_X_READ(index,"name",lengthR); ARGUMENT_X_WRITE(index,"name",lengthR);

    With these macros you must specify the expected length in bytes lengthR or in characters lengthU for the generic types c, x, and n

    ARGUMENT_P_READ(index,"name",lengthR,decimals);

    C_POINTER %_c_pointer void**

    Page 13 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • ARGUMENT_P_WRITE(index,"name",lengthR,decimals);

    With these macros you must specify the expected length in bytes (lengthR) and the number of decimal places (decimals) for the generic type p.

    ARGUMENT_[C_GENERIC|N_GENERIC|CLIKE]_READ(index,"name",size_tU); ARGUMENT_[C_GENERIC|N_GENERIC|CLIKE]_WRITE(index,"name",size_tU); ARGUMENT_X_GENRIC_READ(index,"name",size_tR); ARGUMENT_X_GENERIC_WRITE(index,"name",size_tR);

    With these macros you must specify a variable of the type size_tU or size_tR, containing the length in bytes or characters, for the types C_GENERIC, X_GENERIC, N_GENERIC, and CLIKE.

    ARGUMENT_P_GENERIC_READ(index,"name",size_tR,decimals); ARGUMENT_P_GENERIC_WRITE(index,"name",size_tR,decimals);

    With these macros you must specify a variable decimals (for the decimal places) as well as the length size_tR for the type P_GENERIC.

    ARGUMENT_STRUCT_READ(index,"name",ctype); ARGUMENT_STRUCT_READ(index,"name",ctype);

    With these macros you must specify a suitable C typectype for all structured types STRUCT.

    ARGUMENT_C_POINTER(index,"name");

    This macro is available specifically for the type %_c_pointer. This type is a special internal ABAP type that has exactly the byte length of a C pointer (4, 8, or 16 bytes, depending on platform). The type is always mapped to the predefined ABAP type x. The macros for the type X or X_GENERIC are not used due to the variable length and platform-dependency.

    ARGUMENT_IS_SUPPLIED(index,"name");

    This macro has the same semantics as the logical expression IS SUPPLIED in ABAP. The same consistency checks are executed as for ARGUMENT_READ.

    ARGUMENT_DATA(index,"name",ctype);

    This macro returns the data control block with the C type const DATA *. The same consistency checks are executed as for ARGUMENT_READ. The macro is only active if the include //src/include/abdata.h of the ABAP runtime environment was included.

    Raising Exceptions

    C functions that implement kernel method can raise class-based exceptions.

    Registering Exceptions

    The relevant global exception classes must be registered with an extension of //src/include/abexcpc.h. Local exception classes cannot be registered.

    The exception class is declared in //src/include/abexcpc.h and any text IDs are defined:

    //src/include/abexcpc.h ... CX_ABSTR (CX_..., "CX_...") CX_TXTID (CX_..._bar, CX_..., "BAR") /* special text for class */

    ...

    Classes can also be declared with their standard text only:

    Page 14 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • //src/include/abexcpc.h ... CX_CLASS (CX_..., "CX_...") /* class with standard text */

    ...

    The exact documentation is in the file //src/include/abexcpc.h.

    You must extend the file //src/include/abexcpa.h so that any attributes of an exception class in a C function can be populated; you must specify the name, internal type (according to //src/include/abtypes.h) and the byte length:

    //src/include/abexcpa.h ... CX_ATTR (CX_..._attr1, CX_..., "ATTR1", TYPCSTRING, sizeofR(StrRef)) CX_ATTR (CX_..._attr2, CX_..., "ATTR2", TYPC, LEN_UC2RAW(30))

    ...

    Finally, you must register exceptions as well as arguments in the file //src/krn/runt/abkmeth.sig. This is not forced but, during the syntax check, only registered exceptions are checked for their existence:

    //src/krn/runt/abkmeth.sig ... EXCEPTION(CX_...)

    ...

    Raising Exceptions

    A C function can raise an exception by calling the following macros consecutively:

    EXCEPTION_CREATE(CX_..._bar); EXCEPTION_SET_CSTRING(CX_..._attr1, value, valueLength); EXCEPTION_SET_C (CX_..._attr2, value, valueLength); EXCEPTION_RAISE();

    Within the macros EXCEPTION_CREATE or EXCEPTION_RAISE, a long jump to Extri always takes place, which means that the C function that implements the kernel method is exited in a long jump and the ABAP runtime environment takes control. Therefore, the C function should release its temporary memory before raising an exception. If the exception is caught in ABAP using CATCH without the INTO addition, the long jump takes place in EXCEPTION_CREATE. If the exception is caught with the INTO addition (the exception object is used) or not at all, the long jump takes place in EXCEPTION_RAISE.

    The exceptions are processed in the runtime environment, as if they were raised in ABAP and the same dynamic checks are executed.

    Currently, the following macros, which can be extended if necessary, are available for setting exception attributes. Strings, integer and C fields are supported. See the above sequence for use.

    EXCEPTION_SET_CSTRING_UC EXCEPTION_SET_C

    Value with length specified

    EXCEPTION_SET_C_UC EXCEPTION_SET_INT

    Value with null termination

    Auxiliary Program for Kernel Methods

    The ABAP program RSKMETH serves as a browser for the registration of kernel modules. You can use it to ascertain which C functions are registered for which kernel methods and which arguments/exceptions are registered for these functions. This is helpful when analyzing syntax errors, since kernel methods process

    Page 15 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • information that only exists in the kernel modules.

    Example

    The following example is a simplified calculation class for floating decimal place numbers. The class has an instance attribute in which the last result of each calculation is stored. A method executes a division and is implemented as a kernel method. If the divisor is zero, the method triggers a class-based exception.

    Declaration Section of the Class in ABAP

    CLASS cl_my_calculation DEFINITION ... ... DATA last_result TYPE decfloat16. ... METHODS div IMPORTING p_dividend TYPE decfloat16 p_divisor TYPE decfloat16 RETURNING VALUE(p_result) TYPE decfloat16. ...

    ENDCLASS.

    Signature File //src/krn/runt/abkmeth.sig in the kernel

    ... KERNEL_METHOD(CL_MY_CALCULATION, DIV, xx_myDiv,4) ARGUMENT_F(1, "P_DIVIDEND", TYPE, "F", READ) ARGUMENT_F(2, "P_DIVISOR", TYPE, "F", READ) ARGUMENT_F(3, "P_RESULT", TYPE, "F", WRITE) ARGUMENT_F(4, "ME->LAST_RESULT",TYPE, "F", WRITE) EXCEPTION("CX_MY_DIV_BY_ZERO")

    ...

    C++ source code //src/krn/.../mycalc.cpp in the kernel

    #include "abkmeth.h" ... externC void xx_myDiv( ARGUMENTS ){ const SAP_DOUBLE *const dividend = ARGUMENT_F_READ(1,"P_DIVIDEND"); const SAP_DOUBLE *const divisor = ARGUMENT_F_READ(2,"P_DIVISOR"); SAP_DOUBLE *result = ARGUMENT_F_WRITE(3,"P_RESULT"); SAP_DOUBLE *last_result = ARGUMENT_F_WRITE(4,"ME->LAST_RESULT"); if( 0 == *divisor ) { EXCEPTION_CREATE(CX_MY_DIV_BY_ZERO); EXCEPTION_RAISE(); } *result = *dividend / *divisor; *last_result = *result;

    }

    Implementation Section of the Class in ABAP

    CLASS cl_my_calculation IMPLEMENTATION. ... METHOD div BY KERNEL MODULE xx_myDiv. ENDMETHOD. ...

    ENDCLASS.

    3.1.4 Constructors

    Constructors are special methods that produce a defined initial state for objects and classes. The state of an object is determined by its instance attributes and static attributes. You can assign contents to attributes using the

    Page 16 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • VALUE addition in the DATA statement. Constructors are necessary when you want to set the initial state of an object dynamically.

    Like normal methods, there are two types of constructor: instance constructors and static constructors.

    Special rules apply to constructors during inheritance. These rules are not described in this document, but can be found here.

    Instance Constructors

    Each class has one instance constructor. This is a predefined instance method of the constructor class. If you want to use the instance constructor, the constructor method must be declared in a visibility area of the class using the METHODS statement, and implemented in the implementation section. In global classes, the instance constructor can be declared in the public visibility area only, for technical reasons. In local classes, the visibility area in which the instance constructor can be declared must be more general or equal to the instantiability defined by the addition CREATE of the CLASS statement, where the most specialized area is recommended. Unless it is explicitly declared, the instance constructor is an implicit method, which inherits and accesses the interface from the instance constructor in the superclass.

    Instance constructors are called once for each instance. They are called automatically, immediately after you have created an instance using the CREATE OBJECT statement. It is not possible to call an instance constructor directly using the constructor( ... ); see super->constructor( ... ) in the inheritance.

    An instance constructor can contain an interface with IMPORTING parameters and exceptions. You define the interface using the same syntax as for normal methods in the METHODS statement. The fact that there are no exporting parameters shows that constructors only exist to define the state of an object and have no other function. To pass parameters and handle classic exceptions, use the EXPORTING and EXCEPTIONS additions of the CREATE OBJECT statement.

    Static Constructors

    Each class has a single static constructor. This is a predefined public static method of the constructor class. If you want to use the static constructor, you must declare the static method class_constructor in the public section of the declaration part of the class using the CLASS-METHODS statement, and implement it in the implementation part. The static constructor has no interface parameters and cannot raise exceptions. Unless you implement it explicitly, it is merely an empty method.

    The static constructor is called once per class and internal session. The static constructor of a class class is called automatically before the class is accessed for the first time. The static constructor is always called immediately before the class is accessed, with one exception: If your first access to the class is to address a static attribute, the static constructor is executed at the beginning of the processing block (dialog module, event block, procedure) in which access takes place.

    Notes

    The point at which the static constructor is called has not yet been finalized. We can currently ensure only that it will be called before the class is accessed for the first time. For this reason, static methods may be executed before the static constructor was ended.

    The execution sequence of static constructors is dependent on the program flow. Static constructors must be implemented so that they can be executed in any sequence.

    3.1.4.1 Visibility of Instance Constructors

    For technical reasons, the system declares the instance constructor of a class in a visibility area; it is therefore theoretically visible to the appropriate users. However, an instance constructor is only executed during the creation of an object of this class using CREATE OBJECT. Therefore the instance constructor is only visible to those users of a class that can also create objects of this class.

    The additions CREATE PUBLIC|PROTECTED|PRIVATE of the statement CLASS determine whether every user, only the heirs, or just the class itself can create objects of the class. This means that these additions define the actual

    Page 17 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • visibility of the instance constructor. Therefore the following applies:

    The instance constructor of a class defined using CREATE PUBLIC can be called by any user.

    The instance constructor of a class defined using CREATE PROTECTED can only be called by the class itself and its subclasses.

    The instance constructor of a class defined using CREATE PRIVATE can only be called by the class itself.

    This has the following important consequence:

    If a class was defined using CREATE PRIVATE, only the class itself can instantiate itself. Subclasses of this class cannot even instantiate themselves, because they would have to call the superclass constructor using CALL super->constructor (also see Inheritance and Instance Creation).

    3.1.5 Events

    In ABAP Objects, events are declared as components of classes. SAP makes a distinction between instance events and static events. Triggers and handlers can be objects and classes, depending on whether they are instance events, static events, or event handlers.

    Instance events

    Instance events are declared using the EVENTS statement. They can only be triggered in instance methods.

    Static events

    Static events are declared using the CLASS-EVENTS statement. All methods (instance or static) can trigger them, but only static events can be triggered by static methods.

    3.1.6 Data Types and Constants

    Data Types

    Independent Types

    You can use the TYPES statement to define any number of your own ABAP data types within a class. Types are not instance-specific and are only available once for all the objects in the class.

    In particular, it is possible to define data types in the public visibility section of global classes, which makes the use of type groups in this context obsolete.

    Bound Data Types

    Bound data types that occur as properties of instance or static attributes also belong to the static attributes of a class. After a LIKE addition, the class name can be used to access the properties of instance attributes (exceptions to this rule are the statements ASSIGN ... CASTING and SELECT-OPTIONS ... FOR). In addition, a reference variable can be used with an object component selector without the object having previously been generated.

    Constants

    Constants are special static attributes for which values are specified when they are declared. These values cannot be changed later. Use the CONSTANTS statement to declare constants. Constants are not instance-specific - they are only available once for all the objects in the class.

    In particular, it is possible to declare constants in the public visibility section of global classes, which makes the use of type groups in this context obsolete.

    Page 18 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • 4 Inheritance

    The concept of inheritance allows you to derive new classes from existing classes. To do this, you use the INHERITING FROM addition of the CLASS ... DEFINITION. The new class adopts or inherits all components of the existing class. The new class is called subclass, and the existing class is called superclass.

    If you make no further declarations, a subclass contains exactly the components of the superclass. However, only the components of the public, protected, and package visibility section of the superclass are visible in the subclass. Although the private components of the superclass are also contained in the subclass, they are not visible. In a subclass, you can declare private components with the same name as the corresponding components of the superclass. Each class works with its private components. As long as a method inherited from the superclass is not redefined, it uses the private attributes of the superclass and not the possible subclass attributes of the same name.

    If the superclass does not have a private visibility section, the subclass is an exact copy of the superclass. You can, however, add further components to the subclass. These components are used to specialize the subclass in relation to the superclass. If a subclass is then used as the superclass for a new class, you can then define a further level of specialization.

    Each class can have several direct subclasses, but only one direct superclass. ABAP Objects applies the principle of single inheritance. If subclasses inherit from superclasses that are subclasses themselves, all classes involved represent an inheritance tree whose specialization increases the more deeper hierarchy levels are added. Specialization decreases the closer a level is located to the root node of the inheritance tree. The root node of all inheritance trees in ABAP Objects is the predefined empty class object. This class is the most generic class because it does not contain attributes or methods. When you define a new class, you must not explicitly specify this class as a superclass because it always exists implicitly. In the inheritance tree, two neighboring nodes are known as the direct superclass and subclass, while all preceding and succeeding nodes are collectively referred to as superclasses and subclasses. The declaration of the components of a subclass is distributed among all superclasses of the inheritance tree.

    Programming Guideline

    Avoid using deep inheritance hierarchies

    4.1 Redefining Methods

    Each subclass contains the components of all classes that are located between this class and the root node in the inheritance tree. The visibility of a component is always the same and cannot be changed. However, it is possible to redefine the public and protected instance methods of all preceding superclasses using the REDEFINITION addition of the METHODS statement in order to adjust them to the requested specialization. The interface of a redefined method cannot be changed. The method is merely reimplemented under the same name. Constructors cannot be redefined; instead, special rules apply.

    The method declaration remains with the superclass, and its previous implementation is also persisted there. The implementation of the redefinition is generated additionally with the subclass and obscures the implementation of the superclass. A redefined method works with the private attributes of the subclass and not with possible private superclass attributes of the same name.

    Each reference that points to a subclass object uses the redefined method, even if it was typed with reference to a superclass. In particular, this also applies to the self reference me. For example, if a superclass method m1 contains a call [me->]m2( ) or and if m2 is redefined in a subclass, the call of m1 in an instance of the superclass

    causes the original method m2 to be executed and the call of m1 in an instance of the subclass causes the redefined method m2 to be executed.

    Within a redefined method, super->meth can be used to access the obscured method, for example to adopt and supplement its functions.

    4.2 Abstract and Final Methods and Classes

    Using the ABSTRACT and FINAL additions of the METHODS and CLASS statements, you can define abstract and final methods or classes.

    Page 19 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • Abstract methods are declared in abstract classes and cannot be implemented in the same class but only in a subclass of the inheritance tree. Abstract classes can consequently not be instantiated. A non-abstract method is a concrete method. Except for the instance constructor, the concrete instance methods of a class can also call its abstract methods.

    Final methods cannot be redefined in subclasses. Final classes cannot have any more subclasses and constitute the final node of an inheritance tree.

    Note

    In classes that are abstract and final at the same time, only the static components can be used. Instance components can be declared, but these cannot be used. For this reason, it is recommended that you specify both ABSTRACT and FINAL only for static classes.

    4.3 Inheritance and Polymorphism

    Since a subclass contains all components of all superclasses along the inheritance tree and the interfaces of methods cannot be changed, a reference variable typed with reference to a superclass or to an interface implemented by a superclass may contain references to objects of all subclasses of this superclass. This means that the content of a reference variable typed with reference to a subclass can always be assigned to reference variables typed with reference to one of its superclasses or the interfaces of these superclasses (Up Cast). In particular, the target variable can always be typed with reference to the class object.

    A static user can use a reference variable to address the components visible to it, which are contained in the superclass to which the reference variable refers. This means that it cannot address any specializations that have been added to the subclasses. With dynamic accesses, however, all components can be addressed.

    When an instance method is redefined in one or more subclasses, different implementations of the method can be executed after a method call using the same reference variable, depending on where the class of the referenced object is located in the inheritance tree. The feature that different classes have the same interface and can therefore be addressed using reference variables of one type is called polymorphism.

    4.4 Inheritance and Interfaces

    Interfaces are independent constructs in ABAP Objects that support polymorphism of classses. The polymorphism of interfaces is based on the fact that each class implementing an interface can implement the methods of that interface differently. To the outside world, all interface components look similar which is why interface reference variables can point to objects of all classes that implement the associated interface. The interface concept exists independently of and in addition to the inheritance concept.The classes of an inheritance tree can implement any number of interfaces but each interface can be implemented only once in each inheritance tree. This ensures that each interface component comp has a unique name in the entire inheritance tree intf~icomp and that, starting with the class that implements it, it is contained in all subclasses.

    Interface reference variables that can point to a class of the inheritance tree can also point to all subclasses. Having been implemented, interface methods are fully functioning components of a class and can be redefined in subclasses.

    4.5 Inheritance and Visibility

    You cannot change the visibility area to which a component is assigned using inheritance. Component visibility affects inheritance as follows:

    Public components

    The public visibility area of a subclass consists of all its own public components plus the public components of all its superclasses. From outside the class, public components are visible without restrictions.

    Protected components

    The protected visibility area of a subclass consists of all its own protected components plus the protected components of all its superclasses. The protected section is visible only in the class itself and in all its subclasses.

    Page 20 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • Viewed from outside, protected is the same as private.

    Private components

    The private visibility area of a subclass includes only the private components of this class. They are visible only in this class. The private components of superclasses cannot be used in subclasses. Only methods inherited from superclasses use (provided they have not been redefined) the private attributes of the superclass (even if the subclass has private attributes with the same name).

    Example of protected components

    Within a subnode in the inheritance tree, you can always access the protected components of superclasses. The classes involved, such as the static types of reference variables, must however be part of the inheritance tree.

    In the following example, the reference variables lrefx and lref2 can see the protected components of cx in the context of the subclass c2. The static type of lref1 is c1 and is in another subnode of the inheritance tree. It cannot see any protected components of cx, in the context of c2. In a stricter model (C++ or Java), access in this example would only be possible using lref2. Access using lrefx would not be permitted, since it would involve classes (not subclasses) seeing protected components from outside. At present, ABAP extends the view of lrefx but only in a specific context. We intend, however, to introduce a stricter model and forbid access using lrefx. For this reason, you should not use this option; it causes a warning to be displayed in the extended program check.

    CLASS cx DEFINITION. PROTECTED SECTION. METHODS mx. ENDCLASS. CLASS cx IMPLEMENTATION. METHOD mx. ... ENDMETHOD. ENDCLASS. CLASS c1 DEFINITION INHERITING FROM cx. ... ENDCLASS. CLASS c2 DEFINITION INHERITING FROM cx. PUBLIC SECTION. METHODS m2. ENDCLASS. CLASS c2 IMPLEMENTATION. METHOD m2. DATA: lrefx TYPE REF TO cx, lref2 TYPE REF TO c2, lref1 TYPE REF TO c1. lrefx->mx( ). mx( ).

    lref1->mx( ).

  • unique. The pseudo reference super-> can be used in subclasses to access a method of the direct superclass which is hidden as a result of a redefinition.

    4.7 Inheritance and Static Components

    Static components, like all components, exist only once in each inheritance tree, and can be used as of the declaring class:

    A subclass can access all non-private static components of its superclasses. The class in which the static component is declared is always the class that is addressed.

    From outside, the class component selector can be used to access all visible static components. Each class can be specified in which the component exists (that is, the declaring class and each subclass). Regardless of the class name used in the class component selector, however, the class in which the component is declared is addressed.

    The class in which the component is declared is addressed, whether the static component is used internally or externally. This is important for:

    Calling the static constructors. Static constructors are called the first time you address a class. If you address a static component declared in a superclass using the class name of a subclass, only the static constructor of the superclass is called.

    Access to the static attributes A subclass has access to the content of all non-private static attributes of all superclasses. Conversely, a superclass shares its public and protected static attributes with all of its subclasses. When inherited, therefore, static attributes are not assigned to a single class; instead they are assigned to the subtree of the inheritance tree that consists of all subclasses of the defining class. Changes to the values are visible in all involved classes, regardless of the class used to address an attribute.

    The registration of event handlers. If an event handler is declared for a static event of a subclass inherited from a superclass, it can react to this event only if it is triggered by a method of the subclass or one of its subclasses. If the event is triggered in a static method of a superclass, it is not handled, even if the method is called in a subclass or if the name of the subclass is specified.

    Example

    Calls a static method of a superclass using the name of a subclass. Before the method is executed, the static constructor of the superclass is executed, but not the static constructor of the subclass. The method returns the value set in the superclass.

    CLASS c1 DEFINITION. PUBLIC SECTION. CLASS-DATA a1 TYPE string. CLASS-METHODS: class_constructor, m1 RETURNING value(r1) LIKE a1. ENDCLASS. CLASS c1 IMPLEMENTATION. METHOD class_constructor. a1 = 'c1'. ENDMETHOD. METHOD m1. r1 = a1. ENDMETHOD. ENDCLASS. CLASS c2 DEFINITION INHERITING FROM c1. PUBLIC SECTION. CLASS-METHODS class_constructor. ENDCLASS.

    Page 22 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • CLASS c2 IMPLEMENTATION. METHOD class_constructor. a1 = 'c2'. ENDMETHOD. ENDCLASS. DATA v1 TYPE string. START-OF-SELECTION. v1 = c2=>m1( ).

    Example

    This example shows how a subclass is used to change a static attribute of a superclass, and how the change is visible in a subclass of a different path in the inheritance tree.

    CLASS c1 DEFINITION. PUBLIC SECTION. CLASS-DATA a1 TYPE string. ENDCLASS. CLASS c11 DEFINITION INHERITING FROM c1. ... ENDCLASS. CLASS c12 DEFINITION INHERITING FROM c1. ... ENDCLASS. c11=>a1 = 'Hello Sister'. MESSAGE c12=>a1 TYPE 'I'.

    Example

    For an example of static events, see Inheritance Events.

    4.8 Inheritance and Constructors

    There are special rules governing constructors in inheritance.

    Instance Constructors

    Each class has an instance constructor called constructor. This is an exception to the rule that states that component names along a path in an inheritance tree must be unique. The instance constructors of the various classes in an inheritance tree, however, are fully independent of one another.

    Instance constructors of superclasses cannot be redefined in subclasses.

    Instance constructors cannot be called explicitly using constructor( ... ).

    This means that no naming conflicts can occur.

    The instance constructor is called when an object is created using the command CREATE OBJECT. Since a subclass contains all of the visible attributes of its superclasses, which can also be set by instance constructors, the instance constructor of a subclass has to ensure that the instance constructors of all of its superclasses are also called. This requires that the instance constructor of each subclass contains a super->constructor call of the instance constructor of the direct superclass even if it is not explicitly declared. The only exception to this rule are direct subclasses of the root node OBJECT.

    In superclasses without an explicitly defined instance constructor, the implicit instance constructor is called. This automatically ensures that the instance constructor of the immediate superclass is called.

    When instance constructors are called, all of their non-optional input parameters must be populated as follows:

    Page 23 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • Population for CREATE OBJECT Starting from the class of the created objects, the first explicitly defined instance constructor in the associated path of the inheritance tree is respected. This is the instance constructor of the class itself or the first explicitly defined instance constructor of a superclass.

    Population for super->constructor( ... ) Starting from the direct superclass, the first explicitly defined instance constructor in the associated path of the inheritance tree is respected.

    The interface of the first explicitly defined instance constructor is populated in the same way as with a normal method. This means that:

    If no input parameters exist, no parameters are passed.

    Optional input parameters can be populated using EXPORTING.

    Non-optional input parameters must be populated using EXPORTING.

    If there are no explicitly defined instance constructors in the path of the inheritance tree below the root class object, no parameters are passed.

    In both CREATE OBJECT and super->constructor( ... ), the next available explicit instance constructor must be considered, and, if it has an interface, values to passed to it. The same applies to exception handling for instance constructors. When working with inheritances, a precise knowledge of the entire inheritance tree is required. When a class at the bottom of the inheritance tree is instantiated, it may be necessary to pass parameters to the constructor of a class that is much nearer the root node.

    The instance constructor of a subclass is divided into two parts by the call super->constructor( ... ) (demanded by the syntax). In the statements before the call, the constructor behaves like a static method, which means that the self reference me-> cannot be used and the constructor does not have access to the instance

    components of its class. me-> cannot be used and instance components addressed until after the call The statements before the call are used to determine the actual parameters for the interface of the instance constructor of the superclass. Only static attributes or other visible data can be used for this.

    When a subclass is instantiated, therefore, a nested call of the instance constructors from the subclass to the superclasses takes place. Here, however, the instance attributes can only be addressed in the lowest nesting level (which is the top superclass). When the constructors of the lower subclasses are revisited, their instance attributes can be addressed there successively too.

    The methods of subclasses are not visible in constructors. If an instance constructor calls an instance method of the same class using the implicit self reference me, the method is called as it is implemented in the class of the instance constructor, and not in any redefined form that may occur in the subclass being instantiated. This is an exception to the rule that states that, when instance methods are called, the implementation is called in the class to whose instance the reference points.

    Static Constructors

    Every class has a static constructor called class_constructor. With respect to the namespace within an inheritance tree, the same applies to static constructors as to instance constructors.

    The first time a subclass is addressed in a program, the static constructor is called. However, before it can be called, the static constructors of all of its superclasses must already have been executed. A static constructor may only be called once per program. Therefore, when subclass is first addressed, the system looks for the next highest superclass whose static constructor has not yet been called. It calls the static constructor of that class, followed by those of all classes between that class and the subclass addressed.

    4.9 Inheritance and Instantiation

    If you instantiate a subclass you instantiate all the superclasses at the same time, whereby the initialization of superclass attributes is ensured by the call of the superclass constructors, as described in Inheritance and

    Page 24 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • Constructors.

    For each individual class, the CREATE PUBLIC|PROTECTED|PRIVATE additions to the CLASS statement control who can create an instance of the class or, in other words, can call its instance constructor.

    This has the following consequences:

    If you defined a superclass in a path of the inheritance tree using the CREATE PRIVATE addition, outside users cannot instantiate a subclass, and a subclass cannot even instantiate itself, because it has no access to the instance constructor of the superclass.

    It would therefore also be useful to apply the FINAL addition to a class that was defined using the CREATE PRIVATE addition, in order to prevent a derivation of subclasses. Otherwise subclasses of such superclasses have the implicit CREATE NONE addition.

    The only exception to this rule is if a superclass that can be privately instantiated offers its friendship to its subclasses. The direct route is rarely the case here because the superclass must know its subclasses in order for it to be possible. However, a superclass can also offer friendship to an interface which, in turn, can be implemented by its subclasses.

    Conversely, you cannot create objects of subclasses in their superclass, if these are declared using CREATE PROTECTED or CREATE PRIVATE, unless they are friends of its subclasses.

    Overview of all cases

    Superclass with no addition or CREATE PUBLIC

    Whether a friend of the superclass or not, subclasses can have anyCREATE addition. Without addition they inherit the attribute CREATE PUBLIC. The superclass instance constructor is visible to everyone. The subclass controls the visibility of its own instance constructor, independently of the superclass.

    Superclass with CREATE PROTECTED addition.

    Whether a friend of the superclass or not, subclasses can have anyCREATE addition. Without addition they inherit the attribute CREATE PROTECTED. The superclass allows its subclasses unlimited instantiation and therefore also the publishing of its protected instance constructor.

    Superclass with CREATE PRIVATE addition

    Subclass is not a friend of the superclass

    The subclass has the implicit addition CREATE NONE. Because nobody other than the superclass itself can call its instance constructor, the subclass cannot be instantiated. None of the CREATE additions is permitted, because this would always lead to the unauthorized publishing of the superclass constructor.

    Subclass is a friend of the superclass

    If the subclass has no addition, it inherits the attribute CREATE PRIVATE. However, all CREATE additions are permitted. As a friend, the subclass can publish the superclass's private constructor in any form.

    4.10 Inheritance and Events

    After its declaration in a superclass, an event is known in all subclasses of the inheritance tree in which it is visible, and can be triggered in the methods there.

    An event handler can be declared with reference to all classes of the inheritance tree in which the event is visible for the event handler. However, it can only handle events which are triggered in classes which more specific or the same as the class for which it is declared. If the event is triggered in a method of a superclass of the class, for which an event handler is declared it cannot handle it.

    Page 25 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • Note the latter especially when triggering static events in static methods, since a static method is always executed in the class in which it was declared (also refer to Inheritance and Static Components).

    Note

    For event handlers for events declared in interfaces, the above applies correspondingly to the class in which the interface is bound

    Example

    Refer to Inheritance Events.

    5 Interfaces

    The components of a class are divided into visibility sections, and this forms the external point of contact between the class and its user. For example, the public components of a class define its public scope, since all of its attributes and method parameters can be addressed by all users. The protected components form an interface between the class and those classes that inherit from it (subclasses).

    Interfaces are independent structures that allow you to enhance the class-specific public points of contact by implementing them in classes. Different classes that implement the same interface can all be addressed in the same way. Alongside inheritance, interfaces provide one of the pillars of polymorphism, since they allow a single method within an interface to behave differently in different classes. Interface reference variables allow users to address different classes in the same manner. Interfaces can also be nested.

    Defining Interfaces

    Like classes, you define interfaces either globally in the repository or locally in an ABAP program.

    Interface Components

    You can define exactly the same components in an interface as in a class.

    Implementing Interfaces

    Unlike classes, interfaces do not have instances. Instead, interfaces are implemented by classes. The INTERFACES statement in the declaration part of a class is used to implement interfaces in a class. This statement may only appear in the public section of the class, that is, after PUBLIC SECTION. You can modify some interface components to meet the requirements of the class. For example, you can identify methods as abstract or final, or you can assign initial values to attributes.

    When you implement an interface in a class, the components of the interface are added to the other components in the public section. A component comp of an interface intf can be addressed as though it were a member of the class under the name intf~comp.

    The class must implement the methods of all interfaces implemented in it. The implementation part of the class must contain a method implementation for each interface method meth:

    METHOD intf~meth. ... ENDMETHOD.

    Instead of being specified by intf~meth, the method can also be specified by an alias defined using ALIASES.

    Interfaces can be implemented by different classes. Each of these classes is extended by the same set of components. However, the methods of the interface can be implemented differently in each class.

    Interfaces allow you to use different classes in a uniform way using interface reference variables (polymorphism). Interfaces that are implemented in different classes extend the public scope of each class by the same set of components. If a class does not have any class-specific public components, the interfaces define the entire public

    Page 26 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • face of the class.

    Interface Reference Variables

    You use object references in object reference variables to access objects. Instead of creating reference variables with reference to a class, you can also create them with reference to an interface. This kind of reference variable can contain references to objects of classes that implement the corresponding interface. A reference variable obj with reference to an interface intf is declared with the statement DATA obj TYPE REF TO intf. This reference variable allows programs access to precisely those components defined in the interface, that is, the components of an object that have been added to the class-specific components by implementing the interface.

    Accessing Objects Using Interface References

    To generate an object of the class class, you must first declare a reference variable cref with reference to the class. If the class class implements an interface intf, you can assign the class reference variable cref to the interface reference variable iref as follows:

    iref = cref.

    The reference in iref now points to the same object as the reference in cref.

    It is also possible to directly generate an object to which the interface reference variable points initially. In this case, the TYPE addition of the statement CREATE OBJECT must be used to specify a class that implements the interface.

    CREATE OBJECT iref TYPE class.

    If the interface intf contains an instance attribute attr and an instance method meth, you can address the interface components as follows:

    Using the class reference variable (not recommended)

    Accessing an attribute attr: cref->intf~attr

    Calling a method meth: cref->intf~meth

    Using the interface reference variable (recommended):

    Accessing an attribute attr: iref->attr

    Calling a method meth: [CALL METHOD] iref->meth

    Accessing the Static Components of Interfaces

    As far as the static components of interfaces are concerned, you can only use the interface name to access constants.

    Accessing a constant const: intf=>const

    For all other static components of an interface, you can only use object references or the class class that implements the interface.

    Accessing a static attribute attr:class=>intf~attr

    Calling a static method meth: [CALL METHOD] class=>intf~meth

    5.1 Nesting Interfaces

    Interfaces can be nested. An interface can include one or more interfaces as components, which can contain

    Page 27 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • interfaces themselves. An interface that includes another interface is called a compound interface. An interface nested within an interface is called a component interface. An interface that does not contain any compound interfaces is called an elementary interface.

    All interface components of a compound interface have the same level. If a compound interface i3 contains another compound interface i2, its interface component i1 becomes interface component of i3. A compound interface includes each interface component exactly once. A component interface exists only once even if it is used again as a component of another component interface.

    The statement INTERFACES is used for nesting interfaces within an interface definition:

    INTERFACE i3. INTERFACES: i1, i2 ... ENDINTERFACE.

    Here the interface i3 consists of its components and the interfaces i1 and i2. In the compound interface the components of the component interfaces are visible using the interface component selector (~). Within the above definition of i3, expressions such as i1~comp or i2~comp are possible. However, you can define your own names using the ALIASES statement.

    Using Alias Names

    Within interface definitions, the statement ALIASES can be used to assign alias names to the components of component interfaces, and therefore make those nested to a depth greater than one level visible within the interface definition.

    INTERFACE i2. INTERFACES i1. ALIASES alias21 FOR i1~comp1. ENDINTERFACE. INTERFACE i3. INTERFACES i2. ALIASES alias31 FOR i2~alias21. ALIASES alias32 FOR i2~comp2. ENDINTERFACE.

    Accessing Interface Reference Variables

    Reference variables typed with reference to a compound interface can be assigned reference variables typed with reference to one of the component interfaces ( up cast). The latter can be used to address the components of the component interfaces. The opposite case cannot be checked statically and must take place with the casting operator (?=) (down cast).

    INTERFACE i1. DATA comp1. ENDINTERFACE. INTERFACE i2.

    DATA comp2. INTERFACES i1. ENDINTERFACE. INTERFACE i3. INTERFACES i2. ENDINTERFACE. DATA: iref1 TYPE REF TO i1,

    iref2 TYPE REF TO i2, iref3 TYPE REF TO i3. iref2 = iref3.

    Page 28 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • iref1 = iref2. * recommended access: ... iref1->comp1 ... ... iref2->comp2 ... * this access is not recommended: ... iref2->i1~comp1 ... ... iref3->i2~comp2 ...

    Implementing Nested Interfaces in Classes

    When a nested interface is implemented in a class, all associated interfaces are implemented in the class at the same level irrespective of their nesting hierarchy and the class must implement all methods only once.

    INTERFACE i1. DATA comp1. METHODS meth1. ENDINTERFACE. INTERFACE i2. DATA comp2. INTERFACES i1. ENDINTERFACE. INTERFACE i3. DATA comp3. INTERFACES i2. ENDINTERFACE. CLASS class DEFINITION. PUBLIC SECTION. INTERFACES i3. ENDCLASS. CLASS class IMPLEMENTATION. METHOD i1~meth. ... ENDMETHOD. ENDCLASS. DATA cref TYPE REF TO class. DATA iref1 TYPE REF TO i1. DATA iref2 TYPE REF TO i2. DATA iref3 TYPE REF TO i3. iref1 = iref2 = iref3 = cref. * recommended access: ... iref1->comp1 ... ... iref2->comp2 ... ... iref3->comp3 ... * this access is not recommended: ... cref->i1~comp1 ... ... cref->i2~comp2 ... ... cref->i3~comp3 ... ... iref3->i1~comp1 ... ... iref3->i2~comp2 ...

    Page 29 of 51ABAP Keyword Documentation

    17/3/2014saphtmlp://htmlviewer.sap.com/6Aa5YHcp7kEhmJX{mY9oa0/HTML000349.htm

  • ... iref2->i1~comp1 ...

    You can always assign reference variables using up cast. Class reference variables for classes that implement a compound interface can be assigned to all interface references that are typed with reference to an associated interface component. In the class, the interface reference variables know only the components of their respective interfaces. The same applies for assignments between interface reference variables. It is possible to