Sunteți pe pagina 1din 40

ABAP Object oriented programming An Introduction

- Shakeel ur Rahaman Sai Sridhar Ravi Allampallam & Neeraj Jain

Why has object-oriented programming had such a sweeping impact on the Software Development Community?
Object-oriented programming appeals at multiple levels. For managers, it promises faster and cheaper development and maintenance. For analysts and designers, the modeling process becomes simpler and produces a clear, manageable design. For programmers, the elegance and clarity of the object model and the power of object-oriented tools and libraries makes programming a much more pleasant task, and programmers experience an increase in productivity. Everybody wins, it would seem. If theres a downside, it is the expense of the learning curve. Thinking in objects is a dramatic departure from thinking procedurally, and the process of designing objects is much more challenging than procedural design, especially if youre trying to create reusable objects. It is, in fact, difficult to design objects well for that matter, its hard to design anything well. But the intent is that a relatively few experts design the best objects for others to consume. Successful OOP languages incorporate not just language syntax and a compiler, but an entire development environment including a significant library of well-designed, easy to use objects. Thus, the primary job of most programmers is to use existing objects to solve their application problems. The goal of this document is to show you what objectoriented programming is and how simple it can be. The object-oriented approach takes a step further by providing tools for the programmer to represent elements in the problem space. This representation is general enough that the programmer is not constrained to any particular type of problem. We refer to the elements in the problem space and their representations in the solution space as objects. (Of course, you will also need other objects that dont have problem-space analogs.) The idea is that the program is allowed to adapt itself to the lingo of the problem by adding new types of objects, so when you read the code describing the solution, youre reading words that also express the problem. This is a more flexible and powerful language abstraction than what weve had before. Thus OOP allows you to describe the problem in terms of the problem, rather than in the terms of the solution. Theres still a connection back to the computer, though. Each object looks quite a bit like a little computer; it has a state, and it has operations you can ask it to perform. However, this doesnt seem like such a bad analogy to objects in the real world; they all have characteristics and behaviors. A comprehensive introduction to object orientation as a whole would go far beyond the limits of this introduction to ABAP Objects. This documentation introduces a selection of terms that are used universally in object orientation and also occur in ABAP Objects. In subsequent sections, it goes on to discuss in more detail how these terms are used in ABAP Objects.

A Brief Overview
ABAP Objects, the object-oriented (OO) extension to the ABAP language, is available with releases 4.5 and 4.6. Release 4.6 adds inheritance, nested interfaces, and dynamic method invocation. ABAP Objects is a nearly 100 percent upward-compatible extension of ABAP that includes a full set of OO features. ABAP Objects were created because: The business object repository (BOR) already presented an OO view of the system to the outside, and there was a need for a common programming model for both outside and inside. To use the potential benefits of objects within R/3, including better control of complexity, a better means for encapsulation, extensibility, and reuse, and a language basis for patterns and frameworks. To have seamless integration with external object models (DCOM and CORBA). To have objects to be the foundation for a new GUI programming model (to be completed in release 5.0). By integrating the concepts of OO languagesas opposed to using a specific OO languageinto ABAP, the best concepts from these languages could be combined and adapt them, when needed, to our specific needs. The main design goals were: To make ABAP Objects as simple as possible To use only proven OO concepts To comply with external standards whenever possible (for example, to allow mapping to COM, CORBA, and UML) To require much stronger typing (type checking) than traditional ABAP, where type specification is almost always optional.

The Design Environment


Some of ABAP Objects key design elements include: Classes are not structures with methods (as in C++) but a new kind of type. Reference semantics for objects. ABAP is completely value-based. There are no references in the language, and a MOVE always copies its values (even with fieldsymbols). Objects, on the other hand, can only be accessed by references (there are no embedded objects). This results in a clear separation of values and references. An object reference always has reference semantics. This is the only place in ABAP where objects are shared and never copied. Values (the traditional data) are always copied.

Single inheritance with a separate concept of interfaces. Here we follow a path similar to Java. Most multiple inheritance applications are actually interface cases, and the few extra capabilities of multiple inheritances definitely dont warrant the complexity this introduces into the language. ABAP Objects integrates complex concepts, most notably events and dynamic method invocation. Events are introduced similarly to how they exist in Visual Basic. They are outbound methods that can have parameters. This is a natural model for GUI applications. Of course, ABAP Objects has its own storage management (garbage collection) and a suite of tools such as the Class Builder, Class Browser, and debugger support. With release 4.6, the ABAP language is pretty much complete with all object components, inheritance, and nested interfaces. Two main areas of ABAP Objects are still under development: A new GUI programming model and GUI design tool, and the Object Services framework that covers persistence, transaction control, and locking. These should be completed by release 5.0. The fundamental concepts governing object-oriented programs are: Objects Classes Object References

In object-oriented programming, objects usually have the following properties: Encapsulation Inheritance Polymorphism

Essential Components of Object oriented Programming:

1. Data Encapsulation
Encapsulation is a protective wrapper that prevents the code and data from being arbitrarily accessed by the other code defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled through a well defined interface. Objects restrict the visibility of their resources (attributes and methods) to other users. Every object has an interface, which determines how other objects can interact with it. The implementation of the object is encapsulated, that is, invisible outside the object itself. Your objects are made of attributes and methods. Some of these attributes and methods are publicly available, visible from outside the object: These are the interface. Other attributes and methods are reserved for private use of the object itself: These are the implementation. Separating interface from the implementation is the most fundamental design decision you make when you design an Object oriented program. To see the value of dividing the interface from implementation, look at an example you are already familiar with: the automobile. The interface of an automobile is relatively simple and uniform: the steering wheel, the gas pedal, and the brake. You only have to learn to drive once. You dont have to take new lessons whenever the fall line of cars appears. In contrast, the internal workings of the car- the ignition, number of cylinders, fuel injection and so on- can change dramatically from year to year. If you had to directly interact with the ignition system for each different type of automobile, you would find yourself having difficulty in even getting your car started. A well-designed class has these same characteristics. The interface completely describes how the users of your class interact with it. In almost every case this means that the attributes of your class will be hidden and that users will use the classs methods to modify its data. CLASS <class> DEFINITION. PUBLIC SECTION. ... PROTECTED SECTION. ... PRIVATE SECTION. ... ENDCLASS. These areas define the external visibility of the class components, that is, the interface between the class and its users. Each component of a class must be assigned to one of the visibility sections. The Visibility mechanism defines the class interface, which is available to the users. There are three commonly defined types of visibility in object-oriented technology:

Public Section
All of the components (attribute, method, event) declared in the public section are accessible to all the users of the class, and to the methods of the class and any classes that inherit from it. The public components of the class form the interface between the class and its users.

Protected Section
All of the components (attribute, method, event) declared in the protected section are accessible to all the methods of the class and of classes that inherit from it. Protected components form a special interface between a class and its subclasses. Since inheritance is not active in Release 4.5B, the protected section currently has the same effect as the private section.

Private Section
Components (attribute, method, event) that are declared in the private section are only visible in the methods of the same class. The private components are not part of the external interface of the class.

2. Inheritance
Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. As mentioned, most knowledge is made manageable by hierarchical (that is, top-down) classifications. For example, a Golden Retriever is part of the classification dog, which in turn is part of mammal class, which is under the larger class animal. Without the use of characteristics, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Thus, it is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case. Inheritance interacts with encapsulation as well. If a given class encapsulates some attributes, then any subclass will have same attributes plus any that it adds as part of its specialization. This is a key concept which lets object oriented programs grow in complexity linearly rather than geometrically. A new Subclass inherits all of the attributes of all of its ancestors. It does not have predictable interactions with the majority of the rest of the code in the system.

3. Polymorphism
Polymorphism (from the Greek, meaning many forms) is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction and inheritance.

It provides another dimension of separation of interface from implementation, to decouple what from how. Polymorphism allows improved code organization and readability as well as the creation of extensible programs that can be grown not only during the original creation of the project but also when new features are desired. Encapsulation creates new data types by combining characteristics and behaviors. Implementation hiding separates the interface from the implementation by making the details private. This sort of mechanical organization makes ready sense to someone with a procedural programming background. But polymorphism deals with decoupling in terms of types. This ability is critical because it allows many types (derived from the same base type) to be treated as if they were one type, and a single piece of code to work on all those different types equally. The polymorphic method call allows one type to express its distinction from another, similar type, as long as theyre both derived from the same base type. This distinction is expressed through differences in behavior of the methods you can call through the base class.

4. Object
Just as procedures used to build structured programs, objects are used to build Object Oriented Programs. An Object Oriented Program is a collection of objects that are organized for, and cooperate toward, the accomplishment of some goal. In general every Object: Contains Data. The data stores information that describes the state of the object. Has a set of defined behaviors. These behaviors are the things that the object knows how to do and are triggered by sending the object a message Has an Individual identity. This makes it possible to distinguish an object from another, just as its possible to distinguish one program variable from another.

Everything is an Object
Everything is an object. Think of an object as a fancy variable; it stores data, but you can also ask it to perform operations on itself by making requests. In theory, you can take any conceptual component in the problem youre trying to solve (dogs, buildings, services, etc.) and represent it as an object in your program. A program is a bunch of objects telling each other what to do by sending messages. To make a request of an object, you send a message to that object.

More concretely, you can think of a message as a request to call a function that belongs to a particular object. Each object has its own memory made up of other objects. Or, you make a new kind of object by making a package containing existing objects. Thus, you can build up complexity in a program while hiding it behind the simplicity of objects. Every object has a type. Using the parlance, each object is an instance of a class, where class is synonymous with type. The most important distinguishing characteristic of a class is what messages can you send to it? All objects of a particular type can receive the same messages. This is actually a very loaded statement, as you will see later. Because an object of type circle is also an object of type shape, a circle is guaranteed to receive shape messages. This means you can write code that talks to shapes and automatically handle anything that fits the description of a shape. This substitutability is one of the most powerful concepts in OOP.

Some language designers have decided that object-oriented programming itself is not adequate to easily solve all programming problems, and advocate the combination of various approaches into multiparadigm programming languages. An object has an interface. Aristotle was probably the first to begin a careful study of the concept of type. He was known to speak of the class of fishes and the class of birds. The concept that all objects, while being unique, are also part of a set of objects those have characteristics and behaviors in Common was directly used in the first objectoriented language, Simula, with its fundamental keyword class that introduces a new type into a program (thus class and type often used synonymously). Simula, as its name implies, was created for developing simulations such as the classic bank teller problem. In this, you have a bunch of tellers, customers, accounts, transactions, etc.

The members (elements) of each class share some commonality: every account has a balance, every teller can accept a deposit, etc. At the same time, each member has its own state; each account has a different balance, each teller has a name. Thus the tellers, customers, accounts, transactions, etc. can each be represented with a unique entity in the computer program. This entity is the object, and each object belongs to a particular class that defines its characteristics and behaviors. So, although what we really do in object-oriented programming is create new data types, virtually all object-oriented programming languages use the class keyword. When you see the word type think class and vice versa.

Some people make a distinction, stating that type determines the interface while class is a particular implementation of that interface. Once a type is established; you can make as many objects of that type as you like, and then manipulate those objects as the elements that exist in the problem you are trying to solve. Indeed, one of the challenges of object-oriented programming is to create a one-to-one mapping between the elements in the problem space (the place where the problem actually exists) and the solution space (the place where youre modeling that problem, such as a computer). But how do you get an object to do useful work? There must be a way to make a request of that object so it will do something, such as complete a transaction, draw something on the screen or turn on a switch. And each object can satisfy only certain requests. The requests you can make of an object are defined by its interface, and the type is what determines the interface. The idea of type being equivalent to interface is fundamental in object-oriented programming.

5. Class
Classes are the central element of object-orientation. A Class describes a general element or a general concept, for example the abstract concepts Business Partner, Material, Transaction, Equipment or List. Classes realize an abstract data type. Classes contain components: Attributes, Methods and Events. Classes are templates for objects. You can either define a class locally in an ABAP program, or globally in the class library using the Class Builder tool in the ABAP Workbench. The class library is part of the R/3 repository. Class library classes are stored in special programs called class pools. A class pool is automatically generated for each global class that you create with the Class Builder. The Class Builder also generates the coding frame that defines the classes in the class pool. Global classes are visible to all ABAP programs of the R/3 System. To define local classes in an ABAP program, such as a report or a function group, you must type the corresponding statements manually into the program. A local class is visible only inside the program in which it is defined. The data, or variables defined within a Class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. Thus, it is the methods that determine how a classs data can be used. Variables defined within a class are called instance variables because each instance of the class ( that is , each object of the class ) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another.

More importantly You will never actually write the code for an Object: What you write is the pattern that is used to make objects In ABAP Classes are defined between the CLASS and ENDCLASS statements. A class definition consists of a declaration part, in which the components are defined, and an implementation part, in which the methods are implemented. Example: CLASS c_user DEFINITION. PUBLIC SECTION. CLASS-DATA: instance_count type i. DATA: id type i. METHODS: CONSTRUCTOR, display, get_user RETURNING value(p_user) like sy-uname. PRIVATE SECTION. DATA: a_user like sy-uname. ENDCLASS. CLASS c_user IMPLEMENTATION. METHOD CONSTRUCTOR. a_user = sy-uname. ENDMETHOD. METHOD display. WRITE :/ a_user, id, instance_count. ENDMETHOD. METHOD get_user. p_user = a_user. ENDMETHOD. ENDCLASS.

Class components
Possible class components are attributes, methods and events. Attributes They are the internal data variables within a class. They can have any ABAP data type. We distinguish between instance attributes and static attributes. Instance attributes are declared by DATA and determine the state of an instance. You cannot work with instance attributes without creating an object first. Static attributes are declared by CLASS-DATA and determine the state of a class, which in a way applies to all instances. Static attributes form a data set that is shared by

the whole class and all of its objects. You do not need to create an object to work with static attributes. Methods They are the class procedures. They can access all class attributes and can therefore change the state of an object. They have a parameter interface similar to the interface of function modules. They can have named IMPORTING, EXPORTING, and CHANGING parameters, which can be optional or required and can be passed either by reference or by value. As with attributes, we distinguish between instance methods and static methods. Instance methods are declared by METHODS and can access all the attributes of a class. Static methods are declared by CLASS-METHODS and can only access the static attributes of a class.

METHODS <meth> IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL].. EXPORTING.. [VALUE(]<ei>[)] TYPE type [OPTIONAL].. CHANGING.. [VALUE(]<ci>[)] TYPE type [OPTIONAL].. RETURNING VALUE(<r>) EXCEPTIONS.. <ei>..
When you declare a method, you also define its parameter interface using the additions IMPORTING, EXPORTING, CHANGING, and RETURNING. The additions define the input, output, and input/output parameters, and the return code. They also define the attributes of the interface parameters, namely whether a parameter is to be passed by reference or value (VALUE), its type (TYPE), and whether it is optional (OPTIONAL, DEFAULT). Unlike in function modules, the default way of passing a parameter in a method is by reference. To pass a parameter by value, you must do so explicitly using the VALUE addition. The return value (RETURNING parameter) must always be passed explicitly as a value. This is suitable for methods that return a single output value. If you use it, you cannot use EXPORTING or CHANGING parameters. As in function modules, you can use exception parameters (EXCEPTIONS) to allow the user to react to error situations when the method is executed.

Implementing Methods You must implement all of the methods in a class in the implementation part of the class in a METHOD <meth>. ... ENDMETHOD.

block. When you implement the method, you do not have to specify any interface parameters, since these are defined in the method declaration. The interface parameters of a method behave like local variables within the method implementation. You can define additional local variables within a method using the DATA statement. As in function modules, you can use the RAISE <exception> and MESSAGE RAISING statements to handle error situations. When you implement a static method, remember that it can only work with the static attributes of your class. Instance methods can work with both static and instance attributes. Calling Methods To call a method, use the following statement: CALL METHOD <meth> EXPORTING... <ii> =.<f i>... IMPORTING... <ei> =.<g i>... CHANGING ... <ci> =.<f i>... RECEIVING r=h EXCEPTIONS... <ei> = rc i... The way in which you address the method <method> depends on the method itself and from where you are calling it. Within the implementation part of a class, you can call the methods of the same class directly using their name <meth>. CALL METHOD <meth>... Outside the class, the visibility of the method depends on whether you can call it at all. Visible instance methods can be called from outside the class using CALL METHOD <ref>-><meth>... where <ref> is a reference variable whose value points to an instance of the class. Visible instance methods can be called from outside the class using CALL METHOD <class>=><meth>... where <class> is the name of the relevant class. When you call a method, you must pass all non-optional input parameters using the EXPORTING or CHANGING addition in the CALL METHOD statement. You can (but do not have to) import the output parameters into your program using the IMPORTING or RECEIVING addition. Equally, you can (but do not have to) handle any exceptions triggered by the exceptions using the EXCEPTIONS addition. However, this is recommended.

You pass and receive values to and from methods in the same way as with function modules, that is, with the syntax: ... <Formal parameter> = <Actual parameter> after the corresponding addition. The interface parameters (formal parameters) are always on the left-hand side of the equals sign. The actual parameters are always on the right. The equals sign is not an assignment operator in this context; it merely serves to assign program variables to the interface parameters of the method. If the interface of a method consists only of a single IMPORTING parameter, you can use the following shortened form of the method call: CALL METHOD <method>( f). The actual parameter <f> is passed to the input parameters of the method. If the interface of a method consists only of IMPORTING parameters, you can use the following shortened form of the method call: CALL METHOD <method>(....<ii> =.<f i>...) . Each actual parameter <f i > is passed to the corresponding formal parameter <i i >. Events and Event Handlers As earlier told ABAP supports object oriented features and also in addition to those features, ABAP supports Event handler methods. So our primary question would be

Event Handler Methods Before we step into Event Handler Methods, it is very important to understand and know how methods work in ABAP. Event handler methods are special methods that cannot all be called using the CALL METHOD statement. Instead, they are triggered using events. You define a method as an event handler method using the addition ... FOR EVENT <evt> OF <cif>... in the METHODS or CLASS-METHODS statement.

The following special rules apply to the interface of an event handler method: o The interface may only consist of IMPORTING parameters. o Each IMPORTING parameter must be an EXPORTING parameter of the event <evt>. o The attributes of the parameters are defined in the declaration of the event <evt> (EVENTS statement) and are adopted by the event handler method.

Constructors
Objects must be created at runtime (CREATE OBJECT instruction in ABAP Objects). With their creation they also get their own identity. However, there are no fixed attribute values linked to the identity. How do objects recognize their initial attribute values? Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class. The CONSTRUCTOR concept exists specifically to answer this question. The constructor is a method, which runs automatically during the creation of an object. The constructor allows you to define IMPORTING-parameters. The class constructor is called by the first access to a class element (method, attribute, event, object), the (instance) constructor by the creation of an object (CREATE OBJECT). The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows: METHODS CONSTRUCTOR IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL].. EXCEPTIONS.. <ei>. This is then implemented in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement. The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows: CLASS-METHODS CLASS_CONSTRUCTOR. and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.

Example CLASS vessel DEFINITION. PUBLIC SECTION. METHODS: constructor, drive IMPORTING speed_up TYPE i, get_id RETURNING value(id) TYPE i. PROTECTED SECTION. DATA: speed TYPE i, max_speed TYPE i VALUE 100. PRIVATE SECTION. CLASS-DATA object_count TYPE i. DATA id TYPE i. ENDCLASS. CLASS vessel IMPLEMENTATION. METHOD constructor. object_count = object_count + 1. id = object_count. ENDMETHOD. METHOD drive. speed = speed + speed_up. IF speed > max_speed. speed = max_speed. ENDIF. ENDMETHOD. METHOD get_id. id = me->id. ENDMETHOD. ENDCLASS.

Final methods and classes


By coding FINAL to the statements METHODS and CLASS, you define final (instance) methods or final classes. Final methods can't be redefined in subclasses, and final classes can't have other subclasses. They are always leaves of the inheritance tree. A final class implicitly contains only final methods. You can't and don't need to mark any method of a final class as final. By using FINAL, you protect your methods or classes against unpredictable specialization. When you design an application, you may define as final each method that is not redefined in a subclass or each class that has no subclass. This reduces the danger

of any unknown application inheriting from your classes and getting invalidated when you change your application. Example: CLASS c1 DEFINITION. PUBLIC SECTION. METHODS m FINAL. ... ENDCLASS. CLASS c2 DEFINITION INHERITING FROM c1 FINAL. ... ENDCLASS.

Abstract methods and classes


By adding ABSTRACT to the statements METHODS and CLASS, you define abstract (instance) methods or classes. Abstract classes can't be instantiated. This means there can never be an object belonging to an abstract class. Abstract methods can only be implemented in a subclass, never in a defining class. To implement an abstract method in a subclass, you must declare it in the subclass with the statement METHODS using the addition REDEFINITION Example: CLASS c1 DEFINITION ABSTRACT. PUBLIC SECTION. METHODS m0 ... METHODS m1 ABSTRACT ... ENDCLASS.

CLASS c1 IMPLEMENTATION. METHOD m0. ... ENDMETHOD. ENDCLASS. CLASS c2 DEFINITION INHERITING FROM c1. PUBLIC SECTION. METHODS m1 REDEFINITION. ... ENDCLASS. CLASS c2 IMPLEMENTATION. METHOD m1. ... ENDMETHOD. ENDCLASS. ... DATA o1 TYPE REF TO c1.

CREATE OBJECT o1 TYPE c2. A class containing an abstract method must itself be abstract. Although an abstract class can't be instantiated, reference variables defined with respect to an abstract class make perfect sense. These variables may carry pointers to instances of concrete (that is, non-abstract) subclasses (see the polymorphism section). Abstract instance methods can be used to define signatures for subclass methods without actually implementing them. Since ABAP Objects does not support multiple inheritance, a subclass can't be created from several abstract classes. Instead, you use interfaces. Abstract classes can be used as incomplete templates for several specialized classes. For example, you implement general methods in an abstract class and force all concrete subclasses to implement certain specialized methods with a given signature.

Object References
Each programming language has its own way of manipulating data. Sometimes the programmer must be aware of what kind of manipulation is going on. Are you manipulating on the object directly or are you dealing with some kind of indirect representation that must be treated with a special syntax? You manipulate Objects with References All this is simplified in ABAP. You treat everything as an Object. So, there is a single consistent syntax that uses everywhere. Although you treat everything as an object, the identifier you manipulate is actually a handle or reference to an object. You might imagine this scene as a television (the object) with your remote control (the reference or handle). As long as you are holding this reference, you have a connection to the television, but when someone says, change the channel or lower the volume , what you are manipulating is the reference or handle, which in turn modifies the object. If you want to move around the room and still control the television, you take the remote/handle with you , not the television. Also the remote control can stand on its own, with no television. That is , just because you have a reference or handle doesnt mean theres necessarily an object connected to it. So if you want to hold a counter, which counts, you create as following in ABAP DATA CREF1 TYPE REF TO C_count C_count is a Class and CREF1 is an object reference. The contents of CREF1 are initial. The reference does not point to an instance. But here you have created only the handle or reference but not an object. If you decide to send a message to CREF1 at this point, you will get an error (at runtime ) because CREF1 is not actually attached to anything (theres no television ). A safer practice, then is always to initialize a handle when you create it :

You must create all the Objects before using them. Create object CREF1 . The CREATE OBJECT statement creates an object (instance) of the class C_COUNTER. The reference in the reference variable CREF_1 points to this object. C_counter <1> CREF1 <1>

The CREATE OBJECT statement creates an object (instance) of the class C_COUNTER. The reference in the reference variable CREF_1 points to this object. This instance of the class C_COUNTER is called C_COUNTER<1>, because this is how the contents of the object variable REF_COUNTER_1 are displayed in the debugger after the CREATE OBJECT statement has been executed. This name is only used for internal program administration - it does not occur in the ABAP program itself. The ABAP program can access the public components of the object using the reference variable CREF1, that is in this case, it can call the public methods of the class C_COUNTER

6. Interfaces
Classes, their instances (objects), and access to objects using reference variables form the basics of ABAP Objects. These means already allow you to model typical business applications, such as customers, orders, order items, invoices, and so on, using objects, and to implement solutions using ABAP Objects. However, it is often necessary for similar classes to provide similar functions that are coded differently in each class but which should provide a uniform point of contact for the user. For example, you might have two similar classes, savings account and check account, both of which have a method for calculating end of year charges. The interfaces and names of the methods are the same, but the actual implementation is different. The user of the classes and their instances must also be able to run the end of year method for all accounts, without having to worry about the actual type of each individual account. ABAP Objects makes this possible by using interfaces. Interfaces are independent structures that you can implement in a class to extend the scope of that class. Its components and visibility sections define the class-specific scope of a class. For example, the public components of a class define its public scope, since all users can address all of its attributes and method parameters. The protected components of a class define its scope with regard to its subclasses. (However, inheritance is not supported in Release 4.5B). Interfaces extend the scope of a class by adding their own components to its public section. This allows users to address different classes via a universal point of contact.
.

Interfaces, along with inheritance, provide one of the pillars of polymorphism, since they allow a single method within an interface to behave differently in different classes. Defining Interfaces Like classes, you can define interfaces either globally in the R/3 Repository or locally in an ABAP program. For information about how to define local interfaces, refer to the Class Builder section of the ABAP Workbench Tools documentation. The definition of a local interface <intf> is enclosed in the statements: INTERFACE <intf>. ... ENDINTERFACE. The definition contains the declaration for all components (attributes, methods, events) of the interface. You can define the same components in an interface as in a class. The components of interfaces do not have to be assigned individually to a visibility section, since they automatically belong to the public section of the class in which the interface is implemented. Interfaces do not have an implementation part, since their methods are implemented in the class that implements the interface. Interfaces can be marked as abstract. No worthwhile default implementation can be specified for abstract interfaces. With objects that support abstract interfaces, the inherited attributes and methods must be redefined and implemented.

Implementing Interfaces Unlike classes, interfaces do not have instances. Instead, classes implement interfaces. To implement an interface in a class, use the statement INTERFACES <intf>. in the declaration part of the class. This statement may only appear in the public section of the class. 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 <icomp> of an interface <intf> can be addressed as though it were a member of the class under the name <intf~icomp>. 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 <imeth>: METHOD <intf~imeth>. ... ENDMETHOD. Different classes can implement interfaces. 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 references (polymorphism). For example, 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 face of the class. If an object supports an interface, it must fully support/offer all methods, attributes and events in the interface. Interface References Reference variables allow you to access objects. Instead of creating reference variables with reference to a class, you can also define them with reference to an interface. This kind of reference variable can contain references to objects of classes that implement the corresponding interface. To define an interface reference, use the addition TYPE REF TO <intf> in the TYPES or DATA statement. <intf> must be an interface that has been declared to the program before the actual reference declaration occurs. A reference variable with the type interface reference is called a interface reference variable, or interface reference for short. An interface reference <iref> allows a user to use the form <iref>-><icomp> to address all visible interface components <icomp> of the object to which the object reference is pointing. It allows the user to access all of the components of the object that were added to its definition by the implementation of the interface.

Addressing Objects Using Interface References To create an object of the class <class>, you must first have declared a reference variable <cref> with reference to the class. If the class <class> implements an interface <intf>, you can use the following assignment between the class reference variable <cref> and an interface reference <iref> to make the interface reference in <iref> point to the same object as the class reference in <cref>: <iref> = <cref> 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 <cref>: To access an attribute <attr>: <cref>-><intf~attr> To call a method <meth>: CALL METHOD <cref>-><intf~meth> Using the interface reference variable <iref>: To access an attribute <attr>: < iref>-><attr> To call a method <meth>: CALL METHOD <iref>-><meth> As far as the static components of interfaces are concerned, you can only use the interface name to access constants: Addressing 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: Addressing a static attribute <attr>: < class>=><intf~attr> Calling a static method <meth>: CALL METHOD <class>=><intf~meth> Assignment Using Interface References Casting Like class references, you can assign interface references to different reference variables. You can also make assignments between class reference variables and interface reference variables. When you use the MOVE statement or the assignment operator (=) to assign reference variables, the system must be able to recognize in the syntax check whether an assignment is possible. Suppose we have a class reference <cref> and interface references <iref>, <iref1>, and <iref2>. The following assignments with interface references can be checked statically: <iref1> = <iref2> Both interface references must refer to the same interface, or the interface of <iref1> must contain the interface <iref2> as a component. <iref> = <cref> The class of the class reference <cref> must implement the interface of the interface reference <iref>. <cref> = <iref> The class of <cref> must be the predefined empty class OBJECT. In all other cases, you would have to work with the statement MOVE...? TO or the casting operator (? =). The casting operator replaces the assignment operator (=). In the MOVE... ? TO statement, or when you use the casting operator, there is no static type check. Instead, the system checks at runtime whether the object reference in the source variable points to an object to which the object reference in the target variable can also point. If the assignment is possible, the system makes it, otherwise, the catch able runtime error MOVE_CAST_ERROR occurs. You must always use casting for assigning an interface reference to a class reference if <cref> does not refer to the predefined empty class OBJECT: <cref> ?= <iref> For the casting to be successful, the object to which <iref> points must be an object of the same class as the type of the class variable <cref>. Interfaces - Introductory Example The following simple example shows how you can use an interface to implement two counters that are different, but can be addressed in the same way. *---------------------------------------------------------------------* * INTERFACE I-counter DEFINITION *---------------------------------------------------------------------* INTERFACE I_COUNTER.

METHODS: SET_COUNTER IMPORTING VALUE(SET_VALUE) TYPE I, INCREMENT_COUNTER, GET_COUNTER EXPORTING VALUE(GET_VALUE) TYPE I. ENDINTERFACE. *---------------------------------------------------------------------* * CLASS c_counter1 DEFINITION *---------------------------------------------------------------------* CLASS C_COUNTER1 DEFINITION. PUBLIC SECTION. INTERFACES I_COUNTER. PRIVATE SECTION. DATA COUNT TYPE I. ENDCLASS. *---------------------------------------------------------------------* * CLASS c_counter1 IMPLEMENTING INTERFACE I-counter *---------------------------------------------------------------------* CLASS C_COUNTER1 IMPLEMENTATION. METHOD I_COUNTER~SET_COUNTER. COUNT = SET_VALUE. ENDMETHOD. METHOD I_COUNTER~INCREMENT_COUNTER. ADD 1 TO COUNT. ENDMETHOD. METHOD I_COUNTER~GET_COUNTER. GET_VALUE = COUNT. ENDMETHOD. ENDCLASS. *---------------------------------------------------------------------* * CLASS c_counter2 DEFINITION *---------------------------------------------------------------------* CLASS C_COUNTER2 DEFINITION. PUBLIC SECTION. INTERFACES I_COUNTER. PRIVATE SECTION. DATA COUNT TYPE I. ENDCLASS. *---------------------------------------------------------------------* * CLASS c_counter2 IMPLEMENTING INTERFACE I-counter *---------------------------------------------------------------------* CLASS C_COUNTER2 IMPLEMENTATION. METHOD I_COUNTER~SET_COUNTER.

COUNT = ( SET_VALUE / 10) * 10. ENDMETHOD. METHOD I_COUNTER~INCREMENT_COUNTER. IF COUNT GE 100. MESSAGE I042(00). COUNT = 0. ELSE. ADD 10 TO COUNT. ENDIF. ENDMETHOD. METHOD I_COUNTER~GET_COUNTER. GET_VALUE = COUNT. ENDMETHOD. ENDCLASS. The interface I_COUNTER contains three methods SET_COUNTER, INCREMENT_COUNTER, and GET_COUNTER. The classes C_COUNTER1 and C_COUNTER2 implement the interface in the public section. Both classes must implement the three interface methods in their implementation part. C_COUNTER1 is a class for counters that can have any starting value and are then increased by one. C_COUNTER2 is a class for counters that can only be increased in steps of 10. Both classes have an identical outward face. It is fully defined by the interface in both cases.

7. Garbage Collection and its importance


After knowing about Data Encapsulation, Inheritance, Polymorphism and Event Method Handlers its time to know little about Garbage collection. Since objects are dynamically allocated by using the Create keyword in ABAP, you might be wondering how such objects are destroyed and their memory released for later reallocation. ABAP takes a different approach it Handles de allocation for you dynamically. The technique that accomplishes this is called Garbage Collection. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by an object exist, that object is assumed to be no longer needed and the memory occupied by the object can be reclaimed. Garbage Collection only occurs sporadically (if at all) during the execution of the program. It will not occur simply because one or more objects exist that are no longer used. An object exists for as long as it is being used in the program. An object is in use by a program for as long as at least one-reference points to it, or at least one method of the object is registered as an event handler. As soon as there are no more references to an object, and so long as none of its methods are registered as event handlers, it is deleted by the automatic memory management (garbage collection). The ID of the object then becomes free, and can be used by a new object.

Cleanup is a special problem because its easy to forget about an element when you are done with it , since it no longer concerns you. Thus, the resources used by that element are retained and you can easily end up running out of resources (most notably memory)

Sample ABAP Program to demonstrate Encapsulation , Inheritance, polymorphism and Garbage Collection.

REPORT PROGRAM . *---------------------------------------------------------------------* * CLASS SHAPE DEFINITION *---------------------------------------------------------------------* CLASS shape DEFINITION. PUBLIC SECTION. METHODS: get_area. PROTECTED SECTION. DATA area TYPE p DECIMALS 4. ENDCLASS. *---------------------------------------------------------------------* * CLASS SHAPE IMPLEMENTATION *---------------------------------------------------------------------*

CLASS shape IMPLEMENTATION. METHOD get_area. WRITE area. ENDMETHOD. ENDCLASS. *---------------------------------------------------------------------* * CLASS CIRCLE DEFINITION *---------------------------------------------------------------------* * In ABAP classes inherit using inheriting from keyword. CLASS circle DEFINITION INHERITING FROM shape. PUBLIC SECTION. METHODS: set_radius IMPORTING value(set_value) TYPE i, get_area REDEFINITION. PRIVATE SECTION. DATA radius TYPE i. DATA pi TYPE p DECIMALS 4. ENDCLASS. *---------------------------------------------------------------------* * CLASS CIRCLE IMPLEMENTATION *---------------------------------------------------------------------* CLASS circle IMPLEMENTATION. METHOD set_radius. pi = '3.714'. radius = set_value. ENDMETHOD. METHOD get_area. area = pi * radius * radius . WRITE : 'AREA OF Circle '. * Calling Super Class Method (Shape class) to show * Polymorphism CALL METHOD super->get_area. ENDMETHOD. ENDCLASS.

*---------------------------------------------------------------------* * CLASS TRIANGLE DEFINITION *---------------------------------------------------------------------* CLASS triangle DEFINITION INHERITING FROM shape. PUBLIC SECTION. METHODS: set_length IMPORTING value(set_value) TYPE i, set_breadth IMPORTING value(set_value) TYPE i, get_area REDEFINITION. PRIVATE SECTION. DATA length TYPE i. DATA breadth TYPE i. ENDCLASS. *---------------------------------------------------------------------* * CLASS Triangle IMPLEMENTATION *---------------------------------------------------------------------* CLASS triangle IMPLEMENTATION. METHOD set_length. length = set_value. ENDMETHOD. METHOD set_breadth. breadth = set_value. ENDMETHOD. METHOD get_area. DATA const TYPE p DECIMALS 2 VALUE '0.5'. area = const * length * breadth . WRITE:'AREA OF Triangle' . CALL METHOD super->get_area. ENDMETHOD. ENDCLASS. START-OF-SELECTION. DATA cref TYPE REF TO circle. DATA tref TYPE REF TO triangle. CREATE OBJECT cref. CREATE OBJECT tref. CALL METHOD cref->set_radius EXPORTING set_value = 5.

CALL METHOD tref->set_length EXPORTING set_value = 5. CALL METHOD tref->set_breadth EXPORTING set_value = 5. CALL METHOD cref->get_area. SKIP. CALL METHOD tref->get_area. * Demonstrating Garbage Collection. DATA cref1 TYPE REF TO circle. DATA cref2 LIKE cref. CREATE OBJECT :cref1,cref2. MOVE cref1 TO cref2. CLEAR cref1. cref2 = cref. * The effect of the assignment statement is to copy the reference from * CREF to CREF2. As a result, the reference in CREF2 also points to * the object CIRCLE<1>. No more references point to the object * CIRCLE<2>, and it is automatically deleted by the garbage * collection The internal name CIRCLE<2> is now free again. CALL METHOD cref2->set_radius EXPORTING set_value = 2. SKIP. CALL METHOD cref->get_area. CREATE OBJECT cref1. End of Program When the below statement is executed, Create object: cref1 , cref2 . Pictorially it would look like CIRCLE <1>

Cref1
.

CIRCLE <2> Cref2

But after the statement Move cref1 to cref2. Both the references point to the same memory location. CIRCLE <1> CIRCLE <2>

Cref1 Cref2 And after Clear cref1. Cref1 will be no longer able to refer to any memory. In fact it was made eligible for Garbage Collection. But still, cref2 will be pointing to the CIRCLE <1>

CIRCLE <1>

Cref1

Cref2

Object Orientation Tools of SAP


ABAP Class Builder
The Class Builder allows you to create and maintain global ABAP classes and interfaces. Both of these object types, like global data types, are defined in the ABAP Dictionary. The Class Builder is a fully integrated tool in the ABAP Workbench that allows you to create, display, and maintain global object types from the class library. Features Use the Class Builder to:

Display an overview (in the Class Browser) of global object types and their relationships. Maintain existing global classes or interfaces. Create new classes and interfaces. Create and specify the attributes, methods, and events of global classes and interfaces. Define internal types in classes. Implement methods. Maintain local auxiliary classes. Test classes or interfaces in a simulated runtime environment.

Initial Screen [Transaction SE24]

Class Browser
Use the Class Browser to display global ABAP classes and interfaces or business object types from the class library. The Class Browser enables you to:

Display an overview of existing classes, interfaces, and business object types. Display the relationships between object types. Switch from the overview to maintain an individual object type.

Integration The Class Browser is an integrated part of the Class Builder. You can start it either from the Class Builder, or using Transaction CLABAP. Features 1. Display There is a range of pre-configured views that you can use to display object types. You can also set a selection of filters to meet particular display requirements.

All classes Displays all classes and interfaces in the R/3 class library. The display is based on the R/3 component hierarchy. Business objects Displays business object types from the R/3 class library. Other settings You can adapt the display further by setting filters. There are three separate selection criteria:

1. Object types You can select object types by type, status, and transport attributes. 2. Relationships You can select object types based on the relationships between them. 3. Other You can use this filter to set whether the object types should be selected according to the component hierarchy or not. 2. Maintenance You can switch from the display to maintain an object type by doubleclicking it. The system starts the Class Editor of the Class Builder. You can then switch to change mode and modify the object type. 3. Restrictions You cannot create new object types from the Class Browser.

Initial Screen [CLABAP]

If you choose All Classes then the following screen will be displayed.

Otherwise, if chosen Business Objects, then the following screen will be displayed.

Object Builder [SWO1]


You can use the Object Builder to navigate through a list of development objects. Development objects are the components you use to build an application. You can also view a single development object.

When an object is selected, the following screen will be displayed.

Object Oriented ABAP Some Features and Restrictions.

1. Returning method can be used only in expressions.


If a method only has IMPORTING parameters and one RETURNING parameter, it can be used as an operand in an expression, but it cannot be used in statements like WRITE etc. Example: REPORT ZVV0003. *----------------------------------------------------------------------* CLASS c_time DEFINITION. PUBLIC SECTION. METHODS: CONSTRUCTOR, get_time returning value(p_time) like sy-uzeit. PRIVATE SECTION. DATA A_time like sy-uzeit. ENDCLASS. CLASS c_time IMPLEMENTATION. METHOD CONSTRUCTOR. a_time = sy-uzeit. ENDMETHOD. METHOD Get_time. p_time = a_time. ENDMETHOD. ENDCLASS. *----------------------------------------------------------------------* DATA: o_1 type ref to c_time, w_time like sy-uzeit. END-OF-SELECTION. CREATE OBJECT o_1. * write / o_1->get_time( ). "Error! w_time = o_1->get_time( ). write / w_time. "Ok w_time = o_1->get_time( ) + 5. write / w_time. "Ok

2. Private components of a class.


If a method uses private components of the class, and this method is not redefined and being called from a subclass, it will always use the private components of the super class, even if the subclass has its own private components of the same name.

REPORT ZVV0002. CLASS c_base DEFINITION. PUBLIC SECTION. METHODS: CONSTRUCTOR IMPORTING VALUE(p_name) type string, m_show1, m_show2. PRIVATE SECTION. DATA a_name type string. ENDCLASS. *----------------------------------------------------------------------* CLASS c_derived DEFINITION INHERITING FROM c_base. PUBLIC SECTION. METHODS: CONSTRUCTOR IMPORTING VALUE(p_name1) type string value(p_name2) type string, m_show1 REDEFINITION. PRIVATE SECTION. DATA a_name type string. ENDCLASS. *----------------------------------------------------------------------* CLASS c_base IMPLEMENTATION. METHOD CONSTRUCTOR. a_name = p_name. ENDMETHOD. METHOD m_show1. write: / 'Show1 :', a_name. ENDMETHOD. METHOD m_show2. write: / 'Show2 :', a_name. ENDMETHOD. ENDCLASS. *----------------------------------------------------------------------* CLASS c_derived IMPLEMENTATION. METHOD CONSTRUCTOR. CALL METHOD: SUPER->CONSTRUCTOR EXPORTING p_name = p_name1. a_name = p_name2. ENDMETHOD. METHOD m_show1. write: / 'Show1_r:', a_name. ENDMETHOD. ENDCLASS.

*----------------------------------------------------------------------* DATA o TYPE REF TO c_derived. END-OF-SELECTION. *----------------------------------------------------------------------* CREATE OBJECT o EXPORTING p_name1 = 'Base...' p_name2 = 'Derived...'. CALL METHOD: o->m_show1, o->m_show2.

3. Widening and narrowing cast.


In fact, narrowing and widening casts only change object view to less or more detail, switching the reference variable that points to the object. Both casts do not change real object. It's forbidden to assign object reference to subclass object reference even using widening cast, for example, initializing the extra components with their default values. System-exception move_cast_error will be raised. REPORT ZVV0003. *----------------------------------------------------------------------* CLASS C_BASE DEFINITION. PUBLIC SECTION. METHODS: CONSTRUCTOR IMPORTING VALUE(p_name) type string, m_show. data a_name1 type string. ENDCLASS. *----------------------------------------------------------------------* CLASS C_DERIVED DEFINITION INHERITING FROM c_base. PUBLIC SECTION. METHODS: CONSTRUCTOR IMPORTING VALUE(p_name1) type string value(p_name2) type string, m_show redefinition. DATA a_name2 type string. ENDCLASS. *----------------------------------------------------------------------* CLASS C_BASE IMPLEMENTATION. METHOD CONSTRUCTOR. a_name1 = p_name. ENDMETHOD. METHOD m_show. write: / 'Base:', a_name1, '.'. ENDMETHOD. ENDCLASS. *----------------------------------------------------------------------*

CLASS C_DERIVED IMPLEMENTATION. METHOD CONSTRUCTOR. CALL METHOD: super->constructor exporting p_name = p_name1. a_name2 = p_name2. ENDMETHOD. METHOD m_show. write: / 'Derived:', a_name1, ',', a_name2, '.'. ENDMETHOD. ENDCLASS. *----------------------------------------------------------------------* data: o_1a type ref to c_base, o_1b type ref to c_base, o_2a type ref to c_derived, o_2b type ref to c_derived. *----------------------------------------------------------------------* END-OF-SELECTION. *----------------------------------------------------------------------* CREATE object: o_2a exporting p_name1 = 'First' p_name2 = 'Second', o_1a exporting p_name = '=1st='. o_1b = o_2a. "no problem CALL METHOD: o_1a->m_show, o_2a->m_show, o_1b->m_show. CATCH SYSTEM-EXCEPTIONS move_cast_error = 4. o_2b ?= o_1a. "impossible ENDCATCH. IF sy-subrc = 4. write / 'Cannot cast o_2b ?= o_1a.'. ELSE. CALL METHOD o_2b->m_show. ENDIF. CATCH SYSTEM-EXCEPTIONS move_cast_error = 4. o_2b ?= o_1b. "only casting possible ENDCATCH. IF SY-SUBRC = 4. write / 'Cannot cast o_2b ?= o_1b.'. ELSE. CALL METHOD O_2B->M_SHOW. ENDIF. *----------------------------------------------------------------------*

4. Constructor - optional and default parameters.


Each class has only one instance constructor, which cannot be overloaded. But, using optional and default parameters allows seeming overloading. Report z. CLASS w_test DEFINITION. PUBLIC SECTION. METHODS: CONSTRUCTOR IMPORTING VALUE(p_name) type string optional value(p_date) like sy-datum default sy-datum, show. PRIVATE SECTION. DATA: name type string, date like sy-datum. ENDCLASS. CLASS w_test implementation. ETHOD CONSTRUCTOR. name = p_name. date = p_date. ENDMETHOD. METHOD SHOW. write: / date, name. ENDMETHOD. ENDCLASS. DATA: w1 type ref to w_test, w2 like w1, w3 like w1. END-OF-SELECTION. * use different variants of creating the object instance: CREATE OBJECT w3. CREATE OBJECT w2 exporting p_name = '2nd'. CREATE OBJECT w1 exporting p_date = '20011115' p_name = '1st'. CALL METHOD: w1->show, w2->show, w3->show.

This is not the end. It is just the beginning. Explore the object-oriented world

S-ar putea să vă placă și