46
© IBM Corporation 2013 IBM Global Business Services Fundamentals of ABAP Objects

02 Fundamentals of ABAP Objects

Embed Size (px)

DESCRIPTION

02 Fundamentals of ABAP Objects

Citation preview

ABAP Objects - BasicsObjectives
Upon completion of this chapter, the participants will be able to:
Recognize the concept of Object Oriented Programming (OOP)
Identify the features of Object Oriented Programming & its Advantages
Recall the history of ABAP Object Oriented Programming
Identify the need to learn ABAP Objects
Analyze the basic building blocks of ABAP Objects
Create a local Class with Attributes, Methods, Constructors.
Fundamentals of ABAP Objects
IBM Global Business Services
Features of Procedural Programming Model
Data and Functions are kept separate. Global variables of program contains data, while subroutine contains functions.
Usually non-encapsulated access to data. (exception: Global data of Function Group is only accessible by Function Modules within that group).
Program maintenance as well as management becomes difficult as program size increases.
Very difficult to model real word entity.
Not possible to create several runtime instances easily.
Data
Data
Data
Function
Function
Function
What is Object Oriented Programming (OOP) ?
The fundamental idea behind Object Oriented Programming (OOP) is to combine both data and the functions (methods) those operate on that data into a single unit. Such an unit is called Object.
Possibility of creating several runtime instances is one of the key characteristics of Object Oriented Programming. This allows you to create a direct abstraction of a real world object.
Data
Function
Object
Basic building blocks of OOP
Classes and Objects are the basic building blocks of Object Oriented Programming. When a real world entity is modeled into OOP world then it is known as Class, characteristics as attributes and functionality as methods.
Objects are instances of a Class.
Example :
Inside color is blue
The box is semi open
Functions of the box? (Methods)
It can store things
It can occupy space
Fundamentals of ABAP Objects
IBM Global Business Services
Objects behave like Client/Server systems.
When an objects sends a message to another object, telling it to behave in a particular way, the first object can be seen as a Client and the second as a Server
In OOP services are distributed among objects to avoid redundancy and each object offers only those services that are within its area of responsibility.
If an object needs any other services, it requests these from other objects. This is known as principle of delegation.
Data
Function: GET_DETAILS
Function: RETRIEVE_DETAILS
Abstraction
Modeling real world entities and processes in a more natural way.
Ecapsulation
Hiding data and its related logic behind well defined interfaces.
Inheritance
Polymorphism
Code Reuse
Same code can be reused multiple times by using inheritance.
Fundamentals of ABAP Objects
IBM Global Business Services
Real world entity can be modeled very well.
Provides advance level of data encapsulation that improves the maintainability and stability of ABAP programs.
Better programming structure, reduced maintenance effort & less susceptibility to errors.
Software extension is simpler & more secure.
Stress on data security and access.
Data encapsulation and abstraction.
Once a base class is written and tested, it need not be touched again. Reusing existing code through “Inheritance” saves time, money and increase a programs reliability.
Fundamentals of ABAP Objects
OOP establishes an advanced level of data encapsulation that improves the maintainability and stability of your programs. In procedural programming, a program’s global data area can encompasses a large number of disparate data objects that end up mixed together in a single memory area, where one function might change the application state in a way other functions do not expect. But in OO programming the state is kept in ‘objects’ that separate externally and internally visible data and implementations, ensuring that functions (methods in OO context) work only with the data they should, attributes defining an object’s state remain intact, and applications using that object continue to work correctly.
OOP provides you with the ability to instantiate multiple instances of a single class each with its own variation of characteristics defined in the class, and to use an object’s own functions (methods) to change its state.
OOP greatly enhances code reuse through “inheritance”. With “inheritance” you can derive some or all of the characteristics from a general procedure (method in OO context) into various specialized procedures simply by programming the difference between two, which results in smaller procedures, and in turn improves maintainability.
OOP enables you to work with an object’s business logic through a standalone interface, rather than working with it directly, which relieves you from having to know exactly how a certain functionality is implemented.
OOP makes it easy to incorporate event-driven programming models. Applications can be loosely coupled through a ‘publish and subscribe’ model, where a caller (the event) is not statically bound to the called procedure (the event handler).
IBM Global Business Services
History of ABAP Object Oriented Programming
Object Oriented Programming (OOP) in general was developed at approximately the same time as procedural programming models.
In SAP:
SAP Basis Release 4.5 delivered the first version of ABAP Objects.
SAP Basis Release 4.6 delivered complete version of ABAP Objects by introducing ‘Inheritance’.
SAP Web Application Server 6.10/6.20 enhanced ABAP Objects with Friendship and Object Services.
The object-oriented concept in ABAP is same as other modern object-oriented languages such as C++ or Java.
Fundamentals of ABAP Objects
SAP Basis Release 4.5 delivered the first version of ABAP Objects by extending the ABAP programming language with classes, interfaces and the ability to create objects from classes i.e. class ‘instances’.
SAP Basis Release 4.6 delivered the complete version of ABAP Objects by enabling “Inheritance” which is the key feature of Object-oriented programming for many programmers, and allowing the creation of a compose interface from several component interface.
SAP Web Application server 6.10/6.20 , the successor to SAP Basis, enhanced ABAP Objects with features like “ friendship” between classes and the introduction of Object Services for storing objects in the database.
A small number of concepts that did not prove successful in these other languages were not included in ABAP Objects. On the other hand, ABAP Objects has some features that C++ and Java do not offer.
IBM Global Business Services
Fundamentals of ABAP Objects
ABAP as Hybrid Language
The ABAP runtime support for both the procedural and ABAP Objects programming models
Fundamentals of ABAP Objects
The ABAP runtime support for both the procedural and ABAP Objects programming models enables you to use ABAP Objects classes in any existing ABAP program i.e. in executable programs, module pools, function pools. This enables you to use new techniques based on ABAP Objects, such as new user interfaces, with out the need to completely rewrite your existing code.
ABAP Objects is an extension of the existing ABAP programming language.
ABAP Objects is designed to be downward-compatible.
IBM Global Business Services
ABAP as Hybrid Language (Contd.)
ABAP Objects is not a new language, but a systematic extension of ABAP.
Type checks in ABAP Object context is stricter.
Cleaner Syntax: Obsolete statements lead to syntax errors.
ABAP object statements can be used in procedural ABAP programs.
Object (Classes) can also contain procedural ABAP statements.
Although a pure OO world is technically possible, most real-world implementations use a mixture of procedural ABAP and ABAP Objects.
Fundamentals of ABAP Objects
Although a pure OO world is technically possible, most real-world implementations use a mixture of procedural ABAP and ABAP Objects. ABAP Objects is used in parallel with procedural techniques, and non-OO techniques, such as calling classical procedures or screens, or direct database access. This hybrid programming model of SAP Web Application Server allows you to take advantage of enhance SAP technology.
IBM Global Business Services
Why do we need to learn ABAP Objects ?
To understand the recent concepts of ABAP e.g. BAPI, BAdi, Workflow.
ABAP Objects is the only way you can use new ABAP technology. For example all new GUI concepts, such as the SAP Control Framework (CFW) and Business Server Pages (BSP), are encapsulated in ABAP Objects classes.
For interfacing ABAP with Microsoft technologies or Java as all these are built on the OOP concept.
To take advantage of cleaner syntax and semantic rules.
To exploit the object resource that has been provided by SAP.
Fundamentals of ABAP Objects
IBM Global Business Services
Classes ( Global + Local )
A class is a template/blueprint based on which all objects of the class are created. Class does not occupies any memory space during program execution only the instance of an class (objects) occupies memory space.
In ABAP, classes can be of two types:
Global Class (Created using class builder (SE24) and stored in class repository as Class pool)
Local Class (Created in any ABAP program in global declarations section and only accessible to the programs within the main program.)
Global vs. Local Classes
Where store ?
Tools required to create ?
Any
This example declares and defines a local class “test ”.
The class DEFINITION belongs in the global declarations section at the beginning of the program.
Class definition cannot be nested.
Classes cannot be defined inside subroutines or function modules.
A class definition declares :
Public, Protected and Private.
Definition
Implementation
ENDCLASS.
Fundamentals of ABAP Objects
The class DEFINITION belongs in the global declarations section at the beginning of the program.
The class IMPLEMENTATION processing block need not be at the top of the program.
IBM Global Business Services
Visibility sections in a Class
All components of a class must belong to a visibility section. Components can be public, protected or private.
Public components form the external interface of the class – they are visible to all users of the class as well as to methods within the class and to methods of subclasses.
Protected components form the interface of the class to its subclasses they are visible to methods of the heirs of the class as well as to methods within the class.
Private components can only be used in the methods of the class itself. Using private visibility section is known as Encapsulation or Information hiding.
Notes:
There is no default visibility section in a class.
You should not make attributes public unless absolutely necessary.
While defining local Classes in you must follow the syntactical sequence of PUBLIC, PROTECTED & PRIVATE section.
Fundamentals of ABAP Objects
All components of a class must belong to a visibility section. Components can be Public, Protected or Private.
The declaration part of the class is divided accordingly into up to three sections:
PUBLIC SECTION
All components defined in this section are visible in the subsequent protected and private sections. These are also externally visible.
PROTECTED SECTION
All components in this section can access the components from the public section. In turn, they can be accessed by the components of the private section. These components are externally visible only to the inherited class.
PRIVATE SECTION
All components of this section can access the components of the public and private sections. They are not externally visible.
There is no default visibility section in a class.
The principle of Encapsulation is that the class should hide all unnecessary detail from the users of the class. Adhering to this principle, you should not make attributes public unless absolutely necessary. Since a public attribute can be changed by any user, use of public attribute can easily place the object of a class into an inconsistent state.
IBM Global Business Services
Demonstration
The example program will demonstrate that external users cannot access the protected and private components of a class.
During Syntax check of the program, an error will be generated which will prove that protected and private components of a class cannot be accessed by external users.
Comment out the last two lines to execute the program successfully.
Fundamentals of ABAP Objects
Instance components:
For constants
Instance components exist separately in each instance (object) of the class.
Static components only exist one per class and are valid for all instances of the class.
Static attributes of a class are retained throughout the entire runtime.
Static components are declared with the CLASS- * keywords.
To access instance components, instance component selector (->) is used.
To access static components, static component selector (=>) is used.
Fundamentals of ABAP Objects
Static components can be used without even creating an instance of the class ( Example : Class name => static components )
Constants cannot be modified during the compile time or run time and hence are somewhat like static attributes.
Unlike instance methods, which can access both instance and static attributes, and trigger both instance and static events, static methods can only access static attributes.
IBM Global Business Services
Instance vs. Static components: Elaborated
The class components that share a common memory area for all the class instance are static components.
The class components that have separate memory area for separate instance are instance components.
Object 1 of Class
Object 2 of Class
Object 1 of Class
Object 2 of Class
Memory for Object 1
Memory for Object 2
Memory for Object 1
Demonstration
The example program will demonstrate that Static methods of a class can only use static attributes of that class. It cannot use instance attributes. But, instance methods can use both.
Both the static and instance methods are attempting to display values of the static and instance attributes: STNUM and INSTNUM .
On syntax check, an error will be generated which will demonstrate that static method STMETH cannot work with instance attribute, INSTNUM.
Remove the line in bold in the program and compile. It will get successfully compiled and executed.
Fundamentals of ABAP Objects
Attributes
Attributes contains data that can be stored in the objects of a class.
Attributes can be of 3 types: elementary, structured or table-type.
In classes you can only use TYPE addition to refer to data types and use LIKE reference only for local data objects.
The READ ONLY addition can be used for data declared in PUBLIC SECTION, which means the data can be read from outside, but can be changed only by methods of the same class.
CLASS c1 DEFINITION.
var5 TYPE local_type READ-ONLY,
ENDCLASS.
ENDMETHOD.
ENDCLASS.
Methods are the functionality of a class , ABAP code is written within a method to incorporate the functionality.
Methods are processing blocks with a parameter interface very similar to function modules.
Methods are of two types:
Standard Methods.
This type of methods are written to trap events.
Methods are called with a CALL METHOD statement.
Fundamentals of ABAP Objects
Additions for standard methods:
 3. …RETURNING VALUE (P) : Method that returns values
4. …CHANGING : Method that changes values that is passed
5. ... EXCEPTIONS p1 ... : Methods that raise exceptions
6. ... ABSTRACT : Abstract method
7. ... FINAL : This method cannot be inherited
8. … REDEFINITION : When super class methods is redefine in sub class
If one uses RETURNING parameters, the following restrictions apply:-
(1) No EXPORTING/CHANGING parameters can be used for the method.
(2) Only one RETURNING parameter can be used.
(3) RETURNING parameters are only passed by value.
IBM Global Business Services
Methods (Contd.)
Methods have a signature. With function modules, you should type each parameter but are not forced to do so; with methods, you must type each parameter.
Standard methods are declared, with their parameter interface, in the class definition part and implemented in the class implementation part.
All input parameters (IMPORTING & CHANGING) can have OPTIONAL or DEFAULT addition and then these parameters need not be transferred when the method is called.
If there are more than one OPTIONAL import parameters in a method and no non-optional import parameters without values, one can type in the clause PREFERRED PARAMETER after the list of import parameters to specify which of the optional parameters will get more preference
Fundamentals of ABAP Objects
With OPTIONAL addition the parameter remains initialized according to type, whereas DEFAULT addition allows you to enter a start value.
IBM Global Business Services
Demonstration
This program will demonstrate the use of PREFERRED parameter in methods.
This program contains a class C1 containing method METH1 which has two optional parameters, INPUT1 and INPUT2. Out of them, parameter INPUT2 is declared as PREFERRED parameter. The method simply displays the value of two import parameters .
Notice the last line of the program and see the output. The output will establish that the preferred parameter INPUT2 gets the value passed to the method.
Fundamentals of ABAP Objects
METHODS display_int.
START-OF-SELECTION.
classes.
Objects can only be created and addressed using reference variables.
To use objects:
Create objects, assigning their
Use the object components.
Fundamentals of ABAP Objects
Classes are the templates of objects.
Actual objects must be created and referenced to be of use (except for the static components of a class).
Reference variables (TYPE REF TO) contain references to objects- Users can only access instance objects through reference variables.
To use objects:
Declare reference variables.
Use the object components
The operator ‘->’ is the object component selector.
To access static components of a class use the operator ‘=>’ (class component selector ) with the class name.
Example : (class_name => comp )
Creating a Local Class with different components in different visibility sections
Define and implement Methods
Access the instance and static components of the Class.
Fundamentals of ABAP Objects
IBM Global Business Services
CLASS-METHOD class_constructor
Constructor is a special method that is called by the runtime system as soon as the object is created with the CREATE OBJECT statement.
Useful for:
Sending message about object creation.
Each class has one constructor. It is a predefined with the name CONSTRUCTOR (or CLASS_CONSTRUCTOR for static constructor).
Constructors should be defined in the public area.
Instance constructor
Static Constructor
Fundamentals of ABAP Objects
Constructors are special methods that produce a defined initial state of objects and classes. Constructors are necessary when you want to set the initial state of an object dynamically. The state of an object is determined by its instance attributes and static attributes. You can assign contents to attributes using the VALUE addition in the DATA statement. Constructors are executed once for each instance. They are called automatically after you have created an instance of the class with the CREATE OBJECT statement. A constructor cannot be called with the CALL METHOD statement.
To define a Constructor, simply create a method with the name ‘Constructor’ (a reserved word in ABAP).
IBM Global Business Services
Constructors (Contd.)
Instance constructor can only have IMPORTING PARAMETERS & EXCEPTIONS. It has no EXPORTING parameters because its sole purpose is to initializing the object.
The Static constructor method has no interface parameters.
The Static constructor is called automatically when the class is first accessed:
Creating an instance of the class (CREATE OBJECT)
Accessing a static attribute or Method of the class.
Registering an event handler method for an event in this class.
A static constructor can’t be called explicitly
When exception is raised in an instance constructor, instances are not created, thus no memory space is occupied.
Notes:
There is no Destructor in ABAP Objects. I.e. there is no instance method automatically called immediately before the object is deleted.
Fundamentals of ABAP Objects
IBM Global Business Services
Fundamentals of ABAP Objects
IBM Global Business Services
CLASS class_name DEFINITION DEFERRED.
CLASS class_name DEFINITION LOAD.
If the first access to a global class in a program is to its static components then explicit loading of the class definition is necessary. In release 6.40 this statement is not required.
CLASS class_name DEFINITION CREATE PUBLIC| PROTECTED | PRIVATE.
‘CREATE PUBLIC’ addition is provided automatically by compiler if no create addition is used.
The additions CREATE PROTECTED and CREATE PRIVATE allow you to control the instantiation of your class.
In DELEGATION, two objects are involved in handling a request: the recipient of the request delegates the execution of the request to a delegate.
Fundamentals of ABAP Objects
DELEGATION Example:
The pilot (lcl_client) calls the method get_fuel_level from the airplane class (lcl_airplane). The airplane cannot carry out this task itself. Therefore the airplane calls the get_fuel_level method from the tank class (lcl_tank), that is, the airplane delegates the execution of the method to the tank.
IBM Global Business Services
Demonstration
This program will demonstrate how one can refer to a class without defining the class before that point. But, the class has to be defined later on.
In this program , class C1 has an interface reference O2 declared with reference to class C2. But, before that, class C2 is not defined. It is defined later with a single public attribute, NUM. This demonstrates the theme.
Fundamentals of ABAP Objects
METHODS display_int.
WRITE:/ int,
/ ME->int.
CREATE OBJECT oref.
CALL METHOD oref->display_int.
If an objects internally needs to provide its own reference, it can use the local reference variable “ME”.
“ME” is predefined and always contains a reference to the address of its own object.
Notes:
Local variable of the Method
Variable of the Class
Fundamentals of ABAP Objects
IBM Global Business Services
oref2 TYPE REF TO c1.
START-OF-SELECTION.
Fundamentals of ABAP Objects
IBM Global Business Services
oref2 TYPE REF TO c2.
...
Fundamentals of ABAP Objects
CREATE statement creates an anonymous object of the class that the object reference variable refers and assign the address of that anonymous object to the object reference variable.
The assignment of oref1 to oref2, as we saw leaves oref1 and oref2 pointing to the same object and no reference variable any longer pointing to the object created with reference to c1. That latter object is considered deleted and will be removed from memory by the run time garbage collector. (The garbage collector is a system routine that is automatically started whenever the runtime system does not have more important tasks to carry out.)
CLEAR oref1 initializes the contents of oref1, with the similar affect of deleting the object created with reference to C2 (actually not until you also CLEAR oref2, since oref2 is also pointing to the object of type C2).
Use can use the logical query IF oref1 IS INITIAL to determine whether oref1 contains a null reference (i.e. does not point to any object anymore).
IBM Global Business Services
IMPORTING ex_par = val_im…
CHANGING ch_par = val_chg…
RECEIVING ret_par = val_res...
EXCEPTIONS exception = val_rc…
oref->meth(
IMPORTING ex_par = val_im…
CHANGING ch_par = val_chg…
RECEIVING ret_par = val_res...
EXCEPTIONS exception = val_rc…)
Fundamentals of ABAP Objects
When you call a method that has only IMPORTING parameters, you can omit the exporting addition.
When you call a method that has only one importing parameter, you can specify the actual parameter in parentheses without any other additions.
If there are more than one OPTIONAL import parameters in a method and no non-optional import parameters without values, one can type in the clause PREFERRED PARAMETER after the list of import parameters to specify which of the optional parameters will get more preference compared to others when the method will be called using syntax :- CALL METHOD objref->meth(<val>).
METHODS : METH1 IMPORTING INPUT1 TYPE I OPTIONAL
INPUT2 TYPE I OPTIONAL
PREFERRED PARAMETER INPUT2.
Instance methods are called with CALL METHOD oref-> method_name…but, when you call an instance method within another instance method of the same class, you can omit the instance name oref. The method is automatically executed for the current object.
Static methods are called with CALL METHOD classname=>method_name…but, when you call an static method from within another method of the same class, you can omit the classname. The method is automatically executed for the class of the current object.
IBM Global Business Services
RECEIVING r = a.
var = oref->meth( i1 = a1….in = an).
Instead of CALL METHOD, functional methods can be performed in expressions.
A Functional method can have zero to many IMPORTING parameters, EXCEPTIONS and exactly one RETURNING parameter, that must be passed by value.
A Functional method can be instance or static method.
Operands can be replaced by functional methods
Conventional
Operands can be replaced by functional methods in
Source data objects for the MOVE statement
Logical expressions : IF, ELSEIF, WHILE, CHECK, WAIT
CASE and WHEN expressions
Arithmetic & Bit expressions: COMPUTE
Note : In ABAP Objects all parameters for methods must be fully typed.
IBM Global Business Services
Fundamentals of ABAP Objects
Fundamentals of ABAP Objects
IBM Global Business Services
oref2 TYPE REF TO c1,
oref3 TYPE REF TO c1.
DATA: oref TYPE REF TO c1,
oref_tab TYPE TABLE OF REF TO c1.
START-OF-SELECTION.
CALL METHOD oref->meth.
ENDLOOP.
Pointer tables are used to store multiple instances/objects of same class. This method reduces coding and more elegant against creating separate, separate object reference variables for storing every objects of the same class.
Reference variables are handled like any other data object with an elementary data type.
Fundamentals of ABAP Objects
IBM Global Business Services
Fundamentals of ABAP Objects


Do something to assign meth1 or meth2 to fld at runtime.
fld = ‘METH1’ or ‘METH2’.
CALL METHOD oref->(fld).
Instance, self-reference, and static method can all be called dynamically; the class name for static methods can also be determined dynamically:
Variants:
- oref->(method)
- me->(method)
A method’s parameters can be passed dynamically using PARAMETER-TABLE
and EXCEPTION-TABLE additions to the CALL METHOD statement.
Fundamentals of ABAP Objects
CALL METHOD meth
PARAMETER-TABLE ptab
Internal tables ptab and etab have specific row and table types. See the type group ABAP in the ABAP Dictionary, and the line type ABAP_PARMBIND and the table type ABAP_PARMBIND_TAB. The table has three columns:
NAME for the name of the formal parameter
KIND for the way in which the parameter is to be passed
VALUE with type REF TO DATA for the value of the actual parameter
When assigning the method name to the variable use UPPERCASE name rather than lowercase name.
If you use the PARAMETER-TABLE /EXCEPTION-TABLE addition, you cannot use any other normal additions other than EXCEPTION-TABLE itab.
KIND can therefore be initial. If you want to check the passing method at runtime, you can assign one of the constants of the global class CL_ABAP_OBJECTDESCR to the field:
EXCEPTION-TABLE itab addition allows you to handle the exceptions of a dynamically-called method dynamically. The exception table itab must be a hashed table with table type ABAP_EXCPBIND_TAB or line type ABAP_EXCPBIND. The table has two columns:
NAME for the name of the exception
VALUE with type I for the value to be assigned to SY-SUBRC if the exception occurs.
IBM Global Business Services
This program will demonstrate Dynamic Method calls.
The program contains class C1 with static method (STATM) and instance method (INSTM). The program utilizes syntaxes to call these static/instance methods dynamically.
Fundamentals of ABAP Objects
This program will demonstrate PARAMETER-TABLE & EXCEPTION-TABLE.
This demonstrates, dynamic call of the static method gui_download of the global class cl_gui_frontend_services to store the contents in an internal table in a file on the presentation server. The names of class and method are specified in the strings class and meth. The interface parameters are passed in the internal table ptab and to the execptions of the method return values are assigned using table etab Exceptions that can occur at the method call itself, are handled in a TRY control structure with the statement CATCH.
Fundamentals of ABAP Objects
Abstraction
Ecapsulation
Inheritance
Polymorphism
Code Reuse
Classes and Objects are the basic building blocks of Object Oriented Programming
When a real world entity is modeled into OOP world then it is known as Class, characteristics as attributes and functionality as methods.
Objects is an instance of a Class.
Classes can be of two types:
Global Class (Created using class builder (SE24) and stored in class repository as Class pool)
Local Class (Created in any ABAP program)
Fundamentals of ABAP Objects
IBM Global Business Services
What version of SAP first released ABAP Objects ?
Can class definition be nested ?
Can you define a local class within a subroutine or function module ?
What is the default visibility section in a class ?
Can you call a constructor with the CALL METHOD statement ?
What Interface parameters does a Static Constructor have ?
When is CLASS class_name DEFINITION DEFERRED statement required ?
What parameters does a Functional method have ?
Which transaction we use to maintain global class?
What are the various visibility sections present in a ABAP class?
What is the basic difference between static component and instance component ?
Fundamentals of ABAP Objects
IBM Global Business Services
Questions
Can we access the static component of a class by the object name instead of the class name?
What are the main advantages of Object Oriented Programming over Procedural Programming ?
Fundamentals of ABAP Objects