Do you Know ?

OOPS ABAP Local Classes

INTRODUCTION

Object Oriented Programming
The classical ABAP programming paradigm is giving way to the Object Orientation. Important aspects of Object-Oriented ABAP are data security and reusability.

Advantages of Object Oriented programming
§  Better Programming Structure.
§  Real world entity can be modeled very well.
§  Emphasis on data security and access.
§ Data encapsulation and abstraction.
§  Reduction in code redundancy.

Basic building blocks of OOPs

Classes and Objects are the basic building blocks of Object Oriented Programming. When a real world entity is modeled into OOPs world then it is known as Class, characteristics as attributes and functionality as methods. Object is an instance of a Class.

Example

Consider a box as a class.
The characteristics of the box i.e. colour of the box, size, etc are known as attributes of the class. The functions that a box can performs i.e. it can store things or it occupies space, etc are the methods of the class.












The principal features of ABAP objects are mentioned below :
Abstraction
Modeling real world entities and processes in a more natural way.
Encapsulation
Hiding data and its related logic behind well defined interfaces.
Inheritance
Reusing attributes and methods while allowing for specialization.
Polymorphism
Simplifying by hiding varying implementations behind the same interface.
Code Reuse
Same code can be reused multiple times by using inheritance.

CLASS

The Object-Oriented ABAP has :

Global Class (Created using Class Builder (SE24) and stored in Class repository as Class pool)
Local Class (Created in any ABAP program)

Difference between Global and Local Classes

Global vs. Local Classes
Global Classes
Local Classes
Accessed from?
Any Program
Only within the Program where it is defined
Where store?
In the class repository
In the program where it is defined
Tools required to create?
Class builder (SE24)
With ABAP editor (SE38)
Namespace?
Must begin with ‘Y’ or ‘Z’
Any


Declaring a Class (Local)
A class declaration has two parts.
Definition
Implementation

Classes are template for Objects.  In ABAP program this belongs to Global Section. Class definition cannot be nested. Classes cannot be defined inside subroutines or function modules. 
A class definition declares :
Its components : Attributes, Methods and Events.
The visibility of its components:  Public (default), Protected and Private.

CLASS test DEFINITION.
PUBLIC SECTION.
{ Attributes, Methods, Events }
PROTECTED SECTION.
{ Attributes, Methods, Events }
PRIVATE SECTION.
{ Attributes, Methods, Events }
ENDCLASS.

CLASS test IMPLEMENTATION.
<class body>
{Method implementation is done here}
ENDCLASS.

Components of Class ( Instance + Static )

There are two components of a class
Instance
Instance components exist separately in each instance (object) of the class. To access instance components, instance component selector (->) is used.
Static
Static components only exist one per class and are valid for all instances of the class. Static components are declared with the CLASS-<Attribute/Method> keywords. To access static components, static component selector (=>) is used.


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.


Methods

Methods are the functionality of a class, ABAP codes are written within a method to incorporate the functionality. Methods are processing blocks with a parameter interface very similar to function modules.  Methods are called with a CALL METHOD statement.
Methods are of two types:

Normal Methods :
E.g. METHODS meth.
Event handler methods : This type of methods is written to trap events.
e. g. METHODS meth FOR EVENT evt OF class <Class Name>
                                                 

Constructors

Each class has one constructor. It is a predefined, public instance method of the class, with the name CONSTRUCTOR (or CLASS_CONSTRUCTOR for static constructor). Constructors are special methods that produce a defined initial state of objects and classes. 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.



Objects and Object references

Classes are the templates of objects. The classes has to be instantiated, i.e. Objects must be created and referenced, to be able to use the class methods and attributes (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.
Create objects, assigning their references.
Use the object components

Example :
CLASS c1 DEFINITION.
PUBLIC SECTION.
                        DATA: int TYPE I VALUE ’10’.
METHODS display_int.
ENDCLASS.

CLASS c1 IMPLEMENTATION.
 METHOD display_int.
                        WRITE / int.                 
            ENDMETHOD.
ENDCLASS.

DATA : oref TYPE REF TO c1.                                 Declaration of reference variables                
START-OF-SELECTION.

CREATE OBJECT oref.                                            Creation of objects     

WRITE /  oref-> int.                                                    Using the objects components          
CALL METHOD oref-> display_int.


Inheritance : Concept

The concept of inheritance is used to incorporate the properties of an existing class into a new class. The beauty of this feature is that the methods and the attribute of the existing class need not to be coded into the new class, as well as new features can be added into the new class. Inheritance can be single inheritance (subclass is inherited from a single super class) or multiple inheritance (subclass is inherited from multiple super classes). But ABAP Objects supports only single inheritance. For multiple inheritance, we can inherit from two interfaces, but not from two classes.

Inheritance : Visibility

The public and protected components of the super class are visible in the subclass.  Private section of the super class is not visible in the sub classes.



Real Life Example to demonstrate the advantage of Inheritance

Many things in this world have a main type and then a sub-type. For example, there are humans (main type) and then there are men (sub-type) and women (sub-type). As human beings, men and women share a lot of attributes. We all have arms and legs and a head. We all have faces, toes, and eyeballs, and the list goes on and on of all the things that are similar between men and women. They also do a lot of things that are the same. Most people brush their teeth the same way, work the same way, and eat the same way.

There are differences, the main difference is that all women can have babies and all men cannot have babies. Now let's say that we're given the task of creating classes to define men and women and what they do.

We could create two classes that are 99% the same:
We can see that there will be a lot of duplicate code. And every time we want to add another common property/method for men and women, we have to add it twice - it can quickly become a pain to maintain all of the duplicate code.

It's really inefficient, which is where extending classes comes into play. Extending classes is simply the ability to put all of the common code into one "parent" class (in our example, it would probably be a class called "Human") and then create "child" classes that automatically get all of the parent class code without having to type it in. Then, each child class simply contains whatever is different.


Example :

CLASS scooter DEFINITION.
PUBLIC SECTION.
                        METHODS : storescooter,
                                             display.
            PROTECTED SECTION.
                        DATA  :  noofwheels type i,
                                       noofbrakes type i,
                                       colour type string.
ENDCLASS.

CLASS scooter IMPLEMENTATION.
METHOD storescooter.
                        noofwheels = 2.
                        noofbrakes = 2.
                        colour = 'blue'.
            ENDMETHOD.
            METHOD display.
                        write :/ noofwheels,noofbrakes,colour.
            ENDMETHOD.
ENDCLASS.

CLASS car DEFINITION INHERITING FROM scooter.
            PUBLIC SECTION.
                        METHODS : storecar.
ENDCLASS.

CLASS car IMPLEMENTATION.
            METHOD storecar.
                        noofwheels = 4.
                        noofbrakes = 3.
                        colour = 'red'.
            ENDMETHOD.
ENDCLASS.


DATA : ob TYPE REF TO scooter,
             ob1 TYPE REF TO car.

START-OF-SELECTION.
 CREATE OBJECT ob.
 CREATE OBJECT ob1.

CALL METHOD ob->storescooter.
CALL METHOD ob->display.

CALL METHOD ob1->storecar.
CALL METHOD ob1->display.

Inheritance : Abstract classes and methods

A class defined as ABSTRACT cannot be instantiated, that is one cannot use CREATE OBJECT with reference to the class. Abstract class can only be accessed using its static components or its subclasses. Abstract class serves as a template for subclasses. If a class contains any abstract method the whole class becomes abstract. A method, which is abstract, should be redefined in derived class. An abstract method is the one which is only declared but not implemented.
                             
Example :
CLASS cl_super DEFINITION.
PUBLIC SECTION.
METHODS: demo1   ABSTRACT,
                                                      demo2.
ENDCLASS.

Redefining the Abstract method of Super class in the Sub class
CLASS cl_sub DEFINITION INHERITING FROM cl_super.
PUBLIC SECTION.
METHODS demo1 REDEFINITION.
ENDCLASS.

A method can be re-implemented in the derived class using REDIFINITION keyword. The parameters remain same in the derived class as it was in base class. In the redefined method use the SUPER pseudo reference to access the original method of the base class.


Inheritance : Final classes and methods

A final class can not be inherited further. All Methods of a final class are inherently final and must not be declared as final in the class definition. A final method can not be redefined further.


Interfaces

Like Java, ABAP Objects does not permit multiple inheritance, but using interfaces with inheritance we can achieve the same. Interface is similar to abstract class but it has only definitions part. The interface can be implemented only in the class that uses it. Interface, which is an independent structure, is used to implement in a class to extend the scope of a class. Interface allows users to address different classes via a universal point of contact.

Interfaces are defines as independent construct, in an INTERFACE…. ENDINTERFACE block similar to the declaration block of classes. An interface can declare instance as well as static components like classes. Interface components are always PUBLIC, so visibility is not explicitly defined. Interface defines the methods but do not implement them. Similarly how sub classes implement the methods of an abstract class, all classes that wish to use an interface must implement all of its methods.

Each class can implement one or more interfaces. Interfaces expand public visibility section of the class definition. The class must implement all the methods of each incorporated interface. Multiple classes can implement the same interface. With in the class each component of the interface is identified by the name intf~comp.so identically name components of different interface do not conflict when implemented in the same class. “~” is called interface component selector. A new interface can be created from several existing interface. Such an interface is called a compound interface. An interface which is contained in another interface is called component interface. In a compound interface there is no component hierarchy. All component interfaces are on the same level. So it is not possible to chain names such as I2~I1. A compound interface contains each component interface only once. When a class implements interfaces, each component interface is implemented only once.

Example :
INTERFACE my_interface .
METHODS my_interface_method.
ENDINTERFACE.

CLASS interface_class DEFINITION.
 PUBLIC SECTION.
INTERFACES my_interface.
ENDCLASS.

CLASS interface_class IMPLEMENTATION.
METHOD my_interface~my_interface_method.
DATA: num TYPE I  VALUE 10.
                        Write:/ num.
            ENDMETHOD.
ENDCLASS.


Interfaces : Alias names

Full name of a component in the interface when added in class or another interface is intf~comp, Alias names can be used to replace these names when defining compound interface or declaring interfaces in a class. The class implementation must still refer to the full name.

Events

In ABAP object events use publish and subscribe approach.
A class declares an event and implements a method to raise (publish) the event.
The same and/ or other classes implement a method to respond (subscribe) to the event.
At runtime interested classes and objects register their wish and availability to respond.


Events can be delcared as PUBLIC, PROTECTED, PRIVATE components of any class or interface. Events can be static or instance. Events can be triggered by any method in the class using the RAISE EVENT statement. The parameter interface for events is limited to EXPORTING parameters, passed by VALUE. Events don’t have implementation part. Events have only importing parameters and no exporting parameters.

Event handler methods use the FOR EVENT (event name) OF {CLASS (class name) | INTERFACE (interface name)} addition. Methods are only executed when the event associated with these methods are triggered. An event can have multiple event handler method associated with it. To automatically execute the event handler method when the event is raised, the handler method has to be registered. The registration process is dynamic i.e. the link is established at runtime. The key statement “SET HANDLER” can register the handler method.

Example :

CLASS LCL_DEMO DEFINITION.
PUBLIC SECTION.
                        EVENTS E1.
                        METHODS : M1 FOR EVENT E1 OF LCL_DEMO,
                                             M2.
ENDCLASS.


CLASS LCL_DEMO IMPLEMENTATION.
METHOD M1.
                        WRITE :/ 'HANDLING METHOD'.
            ENDMETHOD.

METHOD M2.
                        WRITE :/ 'RAISING THE EVENT'.
                        RAISE EVENT E1.
ENDMETHOD.
ENDCLASS.



DATA : OBJ TYPE REF TO LCL_DEMO.

START-OF-SELECTION.
CREATE OBJECT OBJ.

SET HANDLER OBJ->M1 FOR OBJ.
CALL METHOD OBJ->M2.