You are on page 1of 23

ABAP OOPS :

Advanced Business Application Programming.

3-tier client/server architecture:


Presentation server: end users will use some GUI. Normally a web interface is being
used. This will be used by users.
Application server: when the instructions are sent from sap GUI from presentation
server they get sent to the application server . this is where all processing happens.
when application server needs to read data or write data to the data base layer it will
communicate with data base layer.
Data base layer: this can be any relational data base system, SQL server and so on.so
now we are having SAP HANA. That manages all reading and writing of data. once its
done its task it will pass the data back to the application server and then application
server will then deliver the data back to the user.

Program namespaces start with A TO X are reserved for sap use means designed and
developed by SAP.
Modifications and programming only possible with a developer key and correct
configuration set up.

SAP SYSTEM LANDSCAPES AND PACKAGES :


Landscape architecture
Development system
Testing system platform independent transport system.
Production system
Typical scenario when we are developing programs:
Create new / selecting existing package.
Create new/ selecting existing transporting request for package.
Create the program.
Enter developer key.
Write code , Debug, save and activate.
Test/ revise as necessary.
Transport.
Creating package: go to se80 and select package and give package, select enter ad click
on yes then give all details and click on create now we need to create a transport
request.
Give description and save your tr.
Now our package is created.
If you want to create a program, click on package (this is context menu) and give
program name.

BASIC ABAP RULES:


ABAP programs are made up of individual sentences/statements.
Each statement begins with a key word.
Case does not matter.
Each statement ends with a period.
ABAP is not spacing sensitive(mostly)
A+B (invalid)
A + B(valid)

DATA TYPES AND VARIABLES:


Data types: Describes the kind of a data a data object(variable) can hold.
Data object: the actual variable or constant defined using a data type.
Complete data types: predefined fixed size with specified-format data storage.
EG: integer, Float, string.
Incomplete Data types: Format is specified but the storage size can vary. you must set
the size when you declare the variable.
EG: character string.
If we don’t specify character string size, default it will take one character size.
ABAP TYPE Type DESCRIPTION
I integer 4 byte
F float 8 bytes
C string up to 65 characters
N numeric string “
String string Dynamic length up to 2GB in size.
Xstring hex string Dynamic length byte sequence up to 2GB in
Size allows for managing the data at byte
level(blobs – instead of ascii etc)
X byte strings up to 65k bytes.
D date 8 characters – yyyy-mm-dd.
T time 6 characters
P packed number precise whole or float numbers up to 16
bytes.
Incomplete data types are string, numeric, string byte sequence and packed number.

DECLARING VARAIBLE:
Data num1 type i.
Data num2 type I value 5.
Data name type c length 20 value ‘Sunil’.
Data num2 like num1.
Data salary type I value ‘2222.66’. ||when specifying decimals u need to use single
Quotes because period will give error.
Chained statements
Data : num1 type I,
String type string,
……
……

DECLARING COMPLEX DATA TYPE VARIABLES:


Data varname type abap_type [length len] [decimals dec] [values val]
Data: temp_text type string val ‘text’, “No need to give size because string manages
the size.
Count type I value 3,
Amount type p length 8 decimals 2 value ‘1.99’.
DECLARING YOUR OWN LOCAL DATA TYPES:
‘TYPES’ Allow you to declare local data types.
TYPES type name TYPE [type specification]
Used to give a standard type more meaning (descriptive name) OR specify a specific
variable structure.
TYPES: age type I,
Enum type n length 8,
Salary type p length 5 decimal 2.
Types cannot have user-specified default value.
Types are local to the program.
if you want to declare global type declarations must use data dictionary.

DECLARING STRUCTURE TYPES:


You can encapsulate multiple data elements in a single structure type.
TYPES : BEGIN of str_emloyee,
Surname type c length 30,
Forename type c length 30
End of str_employee.
No data can be stored in structure yet. It is only a type.
You then use the new TYPE in your data declaration.
If we want to store a data then we need to declare a data object.
DATA employee type str_employee.
Employee-surname = ‘smith’.
Employee-forename = ‘Sunil’.

DECLRING CONSTANTS:
Fixed value data objects that we cannot change the values.
Constants country code type c value ‘GB’.
Constants pi type f value ‘3.14’.
Structure syst is having many system defined variables.
If we want to see structures click on data type and give structure name.

INTERNAL TABLES:
ABAP allows us to copy data between two structures even if they ae not the same type.
Example is we can transfer data between work areas like wa_vbap and wa_vbak.
This will done based on actual component name(field name) of the structure.

Process for creating internal tables:


Define a type for a variable (In our program or ABAP dictionary)
Instantiate (create) 1 or more internal tables based on the type.
We have three types of internal tables.
STANDARD: similar to a data base table – Accessible by row and keys.(we can access
records one row at a time or by using a table key)
SORTED: Data is always sorted by the specific keys- Accessible by rows and keys. we
can access records one row at a time and by using the keys.
Hashed: unique keys only- Accessible by keys only. this is the fastest way of accessing
data in an internal table.
It is defined as hash because, hashed uses a specific algorithm and only used unique
keys to access the data. We don’t have the facility to read the data line by line.

CREATING INTERNAL TABLES:


Standard internal tables.
The system keeps row numbers by using indexes.
Defining key is optional.
Cannot have unique keys, because by definition STANDARD tables allow duplicate keys.
Normal DB tables can have unique keys.
The records are stored in sequential order. Standard tables always allows duplicate
keys.
Define a structure.
Types : BEGIN of str_employee,
Surname type c length 30,
Forename type c length 30,
Id type n length 10.
End of structure.
Define a table type – with a key.
type : employee type standard table of str_employee with non unique key surname
forename.
Data : zemp type employee.
The above table ordered by table key surname and forename.

SORTED INTERNAL TABLE:


A key must be specified.
The system automatically maintains the sort order based on the keys.
Therefore a key must be specified.
The key can be unique or non unique.
[UNIQUE KEY : all values will have to be unique in this key. It can have only one null
valu where as In primary key we don’t have null values].
Types : employee type sorted table of str_employee with unique key id.
Data : zemp type employee.

Hashed internal table :


Access to and order of fields is based on a system managed hashing algorithm.
You must have a key field defined.
Key must be unique.
We are not allowed for non unique keys.
It uses special hashing algorithm to give us super fast access to the records.
No index is maintained by the system.
Types : employee type hashed table of str_employee with unique key id.
Data : zemp type employee.

SUBROUTINES :
Similar to methods / functions in other languages.
Provides encapsulation of functionality.
Permits passing of parameters.
Form mysub.
1 or more statements.
END form.
Perform mysub.
Subroutines are placed at the end of the program.
Subroutines can see and manipulate data – bad practice to do so.
Breaks encapsulation principles.

SUB ROUTINES :
Actual parameters are copied /transferred to the parameters listed in the subroutine
interface.
Methods of passing parameters:
Call by value – the parameter value is copied to the subroutine.
Call by reference – The parameter memory location is passed to the subroutine
resulting in the subroutine operating on actual parameter.
Call by value and result – The parameter value is copied to the subroutine. If the end of
the subroutine is reached with out any errors, the subroutine parameters values are
copied back to the actual (caller ) parameters.
Form mysub.
1 or more statements

..
END FORM.
Perform mysub.

Subroutines example pass by value :


Perform mysub using myvar1. “Subroutine call
Form mysub using value (subvar1) type i. “sub routine definition.
1 or more statements
..
ENDFORM.
INHERITANCE : A class shares its structure and behavior with another class.
POLYMORPHISM : Objects that are different from one other but use the same
communication interface.
EVENTS : objects respond & trigger events.
Object is special type of variable.
An object contains attributes and or methods . attributes or just the basic data types
such as integers, character string or methods.
Vehicles have attributes such as make model and color. These are just variables that will
help describe the object.
A vehicle carries out certain tasks , certain actions and we call these methods .typical
methods for vehicle are things like accelerate , turn and stop.
A class is just a definition of the object.
A class declares the design for an object.
It describes how to create the objects themselves.
Its just like blueprint for a house.
We create a class to enable others to create object instances and when we create an
object instance what we are actually doing is storing an object, a reference in our object
variable.
All the object reference does is point to our object that is stored in memory and is
designed on a particular class.
When we declare a class , first we have to define its definition.
Class myclass DEFINITION we must have both definition and
implementation.
… when we create a class no object is created. We
are
Endclass. juSt defining the blueprint for what objects
based on
Class myclass implementation this class contain and do.

Endclass.
Classes can be defined locally (like this) or globally (using se24 – class builder). The
class builder stores our class in the data dictionary.
OBJECT : An instance of a class. We instantiate an object based on the blueprint. Allows
us to store data/ or allow method execution.
A class definition can define the following.
Types ,constants ,data objects (attributes), and method interfaces.
We can choose how we define the visibility of attributes.
Public : available from outside of the object.
Private : available only within the object itself.
A public attribute may be designed as READ-ONLY.
CLASS – EXAMPLE
Within class definition, The public section must come before the private section.
Class myclass DEFINITION
Public section . [Private section]
TYPES
CONSTANTS
DATA
DATA name TYPE READ-ONLY.
…..
ENDCLASS.
Here we are saying this is read only variable , the only our object, only our object
methods can update it. We still want it made visible to external calling programs , but
we don’t want to allow them to change the variable.
So we can use the read-only addition to declare data objects as read only.
Class student definition.
Public section.
DATA : name type c length 40,
Age type I,
Gender type c length 1 READ-ONLY.
Private section
DATA : LOGINID TYPE c length 20,
Pwd type c length 15.
Endclass.

STATIC ATTRIBUTES:
A static attribute is a shared attribute across all objects based on a class.
It is not dependent on instantiation of each object. This means we can access a static
attribute without creating an object.
Used for things like object counters.
All of the objects in a class have access to static attributes.
Declare them using the class-data statement.
Class myclass definition.
Public section. [private section]
Class-data name type type.
ENDCLASS.
Changing the value of a static attribute will make the changed value visible in all other
objects created from that class.
Static attributes are useful when we want to keep track of things like object counters.
Suppose we created five objects from a specific class, but we can use a static attribute to
keep track. Then we can find how many we created.
All of the objects have access to that same static attribute.
They all reference the same memory area.
Changing the value of a static attribute will make the change to value visible in any
object that is instantiated from that class.
Static attribute declaration:
CLASS-DATA: count type i.

METHODS:
the method definition indicates a methods:
.interface :
Method parameters
Method return type (method signature)
Method exception.
Methods may be designated as public or private.
A private method may only be called from within another method of the
class.
Just as we have class data(static attributes) we can have class-methods too.
These methods may only access static attributes.
Class methods may be invoked using the name of the class or an object of
the class.
An object does not need to be instantiated to invoke a class method.

METHODS – Parameter types


IMPORTING – used to transfer data into a method.
Can be designated as OPTIONAL and can have a DEFAULT value specified.
The value of a parameter can not be changed in the method definition.
EXPORTING: Used to transfer data OUT of a method.
At the end of the method the value of the exporting parameter will be
passed back to the calling program.
CHANGING: A mix of IMPORTING & EXPORTING
Passed into the method for use and can be changed.
Can be designated as OPTIONAL and can have default value specified.
Exported back out to the calling program at the end of the method.
You can use pass by value as well as the default pass by reference.

METHOD DEFINITION
Within the class definition, We define the method definition which specifies the
method’s interface.
.method parameters
.method return type(method signature)
.Method exception.
Methods may be specified as public or private.
A private method may only be called from within another method of the class.

Functional methods
if you want your methods to return a single value , you can create a functional method.
Use RETURNING in the methods interface.
When using returning, the exporting and changing parameters can not be used.
To return the value, you assign the value to the name of the data object identified in the
RETURNING statement.
You do not use a RETURN statement.
This gives us the ability to create Methods that can be called within other statements
such as IF,CASE,MOVE and COMPUTE.
CLASS myclass DEFINITION.
PUBLIC SECTION

Methods Method1 IMPORTING var1 TYPE I OPTIONAL
Value(var2) Type i
Exporting var3 type I
Changing var4 type i.
Methods method2 importing var1 type I default 3
RETURNING value(retval) type i.

Private section
… “attributes/method definitions.
Endclass

METHODS – Implementation
Place the code for the method functionality in the Class implementation.
All parameters and types have already been defined in definition.
Class myclass IMPLEMENTATION.
METHOD Method1.


ENDMETHOD.
METHOD Method2.

Endmethod.
ENDCLASS.
Foe definition, we have to use keyword METHODS but for the implementation we will
use Keyword method.

Defining a new car class


Define a class for a car. Add the following attributes & methods
ATTRIBUTES:
.Make(BMW , Mercedes, Audi etc..)
.Model(3 series, 220, A4 etc..)
.Number of seats
.speed
.max speed
.Number of cars
METHODS:
.SetNumSeats(numSeat)
.Gofaster(increment result)
.Goslower(increment, result)

For number of cars we are going to create static attribute.


When we are creating many instances of this class ,the no of cars would be a counter to
define how many cars have are being created. So we can make this a static attribute.
That means the no of cars attribute will be available to any calling program even it
hasn’t instantiated an object.
Do you need a call in program to be able to update these, and if you don’t that’s when
you would pop them down in a private section.
Read-only will actually mean that they can be accessed from outside but they can only
be read.
CLASS car DEFINITION.
PUBLIC SECTION.
CLASS-DATA: numofcars type i. “ Static attribute.
CLASS-METHODS class_constructor.
METHODS constructor
IMPORTING
Make type c
Model type c
Numseats type i
Maxspeed type i.
METHODS viewcar.
METHODS setnumseats
IMPORTING
Newseatnum type i.
*exporting
*changing
*returning.
METHODS gofaster
IMPORTING
Increment TYPE i
EXPORTING
Result TYPE i.
METHODS goslower
IMPORTING
Increment type i
RETURNING
Value(result) TYPE i.
PRIVATE SECTION.
DATA: make type c LENGTH 20,
Model type c LENGTH 20,
Numseats TYPE I,
Speed type I,
Maxspeed type i.
CLASS-DATA: carlog Type c LENGTH 40. “Used by class_constructor”
ENDCLASS.

CLASS car IMPLEMENTATION.


METHOD class_constructor.
Carlog = ‘car has been used’.
Write: / carlog.
ENDMETHOD.
METHOD constructor.
Me-> Make = make. (we are using me because here attribute and parameters
same name so system will confuse ,in order to avoid the error use another names or self
referencing)
Me-> Model= model.
Me-> Numseats = numseats.
Me->Maxspeed = maxspeed.
Me->Numofcars = numofcars + 1 .
ENDMETHOD.

METHOD viewcar.
WRITE: / ‘Make = ‘, 19 make.
….some write statements.
ENDMETHOD.
METHOD setnumseats.
Numseats = newseatnum.
ENDMETHOD.
METHOD gofaster.
DATA tmspeed TYPE i.
Tmspeed = speed + increment.
IF tmspeed <= maxSpeed.
Speed = speed + increment
ENDIF.
Result = speed.
ENDMETHOD.
METHOD goslower.
DATA tmspeed TYPE i.
Tmspeed = speed - increment.
IF tmspeed >= 0.
Speed = speed - increment
ENDIF.
Result = speed.

ENDCLASS.

START-OF-SELECTION.
DATA car1 TYPE REF TO car.
CREATE OBJECT car1
EXPORTING
Make = ‘Audi’
Model = ‘A4’
Numseats = 5
Maxspeed = 120.
Constructor is executed when an object is instantiated.
Here the tutor moved the attributes to private section because this class updates these
attributes by its own methods. That means a call in program will not be able to update
these attributes directly.

Creating an Object.
Define an object reference variable.
This is a pointer to object of a class.
Create the object
We create an instance(variable name) of the class.
Object definintions
START-OF-SELECTION.
DATA objectname TYPE REF TO classname.
CREATE OBJECT objectname.

Constructor (Instance constructor)


So far we have defined our attributes and methods definition and implementation.
But, we have some attribute values empty that are used by our methods.
This is where we can make use of constructors.

A constructor is a special type of method – A class may define a constructor method.


It is automatically executed by the system when a new object is instantiated.
A class constructor has a fixed name of constructor.
The method must be public and can only have importing parameters.
A constructor is a optional method.
WHY DO WE USE CONSTRUCTORS:
To dynamically set the state of an object.
Initializing attributes for an object.
Allocating resources for the object.
To execute any code that need to happen when a new object is created.

constructor method will get executed for each instance of the class that is created.
Self - reference
When referring to components of a class inside the class itself we normally just use the
component name.
Where we have some ambiguity like in our example we can use the Self-reference
syntax to refer to an objects attributes ,methods and the object itself.
Me->attribute_name
This makes use of the local reference variable me that refers to the object.

STATIC -CONSTRUCTOR
Similar to a normal constructor but is executed the first time a:
. Object of a class is created.
.static attribute of the class is used.
.Static method of the class is used.
Must be declared in the PUBLIC SECTION
No interface parameters can be defined.
Can only access static attributes of their class is called class constructor.
Syntax: CLASS-METHODS class_constructor
First class constructor will be called and later normal constructor method will be called.

USING CLASSES IN OUR PROGRAMS


Classes with static attributes or methods can be referenced without instantiating an
object.
Static attributes(CLASS-DATA)
Static methods(CLASS-METHODS)
Reference a static public attribute:
Classname=>attributename
Var1 = classname=>attributename
Call a static method:
CALL METHOD classname=>methodname.
Classname=>methodname().
Call a instance method
Classname->methodname().
Difference between Static & instance
Static uses => instance uses ->
Calling Methods in our programs
RULES:
.There must not be a space before the opening parenthesis.
.there must be a space after the opening parenthesis.
.if a method imports only one parameter, place the param inside the parenthesis.
Classname->methodname( data ).
.if a method imports more than one parameter , list the param in pairs.
Formal param = actual param
Classname->methodname( param1 = data1 param2 = data2 ).
. if there are parameters other than importing, list the type of param passing.
Classname->methodname(EXPORTING param1 = data1 param2 = data2
IMPORTING param3 = data3 param4 = data4
CHANGING param5 = data5 param6 = data6
Change to => for static methods. We need to read right to left

Parameters passing types of the calling program correspond to the parameter types in a
method. But they are not same.
CODING EXAMPLES OF USING ATTRIBUTES AND METHODS IN A
CALLING PROGRAM

Car1->gofaster( exporting increment = 25 IMPORTING result = theresult ).


We are storing the result of the method In theresult program.

CALLING FUNCTIONAL METHODS


A better way of calling a functional method is
Theresult = car1->goslower ( 5 ).
Car1->viewcar( ).

ABAP OBJECTS WITH INTERNAL TABLES :


Using internal tables is no different in ABAP objects to procedural ABAP coding.
CLASS a_class DEFINITION.
PUBLIC SECTION.
TYPES: a_type TYPE STANDARD TABLE OF atable.
DATA: a_tab TYPE a_type.
METHODS constructor.
ENDLASS.
CLASS a_class IMPLEMENTATION.
METHOD constructor.
Select * from table atable into TABLE a_tab.
…..
ENDMETHOD.
START-OF-SELECTION.
DATA my_class TYPE REF TO a_class.
CREATE OBJECT my_class.

SAPFLI table :
The program provided by SAP to fill these tables in your system is a standard called,
‘SAPBC_DATA_GENERATOR’, which can also be accessed through the standard
transaction ‘BC_DATA_GEN’.
Note: Advisable that you run this program in background mode.
You need to give tcode as bc_data_gen

PUBLIC – Visible outside the class


We can reference attributes and call methods from outside of the class.

PRIVATE- VISIBLE INSIDE THE CLASS ONLY


Now we have to use methods to access this data.

INHERITANCE
Inheritance allows us to define NEW classes from existing ones.
The new class inherits all the attributes and methods of the higher level class.
We can then expand and enhance the new class.
VEHICLE
CAR BOAT TRAIN
BMW AUDI SAIL BOAT SPEED BOAT ELECTRICTRAIN STEAM TRAIN

Inheritance describes on is a relationship.


In real life : A car is a vehicle
A bus is a vehicle.

You might also like