Classes and Objects

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A class is a blueprint that bundles data with the code that works on that data, and an object is one thing built from that blueprint. In the Expense claims example a class zcl_exp_claim_validator holds the spending limit and knows how to say whether a claim amount is acceptable; each object made from it carries its own limit. Almost all modern ABAP is written this way: RAP business objects, ABAP Unit tests, the classes that SAP releases for ABAP Cloud and the handlers behind OData services are all classes. This page explains what a class is made of, who may see each part of it, how methods receive and return values, how an object is created, and how to control who may create objects and who may inherit. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Classes and objects work the same in ABAP Cloud, in classic Standard ABAP, on premise and in the Public Edition; only the places where you may write them differ (global classes are written in ABAP Development Tools, and ABAP Cloud forbids the classic report-style output used by some listings here).

Before you read

Key terms

  • Class: the blueprint that defines the attributes and methods of a kind of object.

  • Object: one instance built from a class, with its own copy of the instance attributes.

  • Attribute: a variable, constant or type that belongs to a class or to its objects.

  • Method: a named block of code of a class, with its own parameters.

  • Visibility section: one of PUBLIC, PROTECTED and PRIVATE, which decides who may use the components declared in it.

  • Constructor: a special method that sets an object or a class up when it is created or first used.

  • Reference variable: a variable that points to an object, declared with TYPE REF TO.

  • Friend: a class that the owner of a class has allowed to see its private components and to create objects of it.

Local and global classes

ABAP has two kinds of class, and the only difference is how far they are visible.

A local class is defined inside a program, or inside a part of another class, and is visible only there. It is the quick way to try an idea in a report and the way ABAP Unit test classes are written. Nobody else can use it, and it is not listed in any repository.

A global class lives in a class pool, an object of its own in the ABAP repository (a class pool holds exactly one global class and any local helper classes it needs). Every program, class and RAP business object in the system may use it, subject to its visibility. Global class names must be unique in the whole system, so customer code starts with the customer namespace prefix Z or Y (this series uses zcl_exp_ for classes of the Expense claims example). You create a global class in ABAP Development Tools (ADT) in Eclipse, the strategic and, for ABAP Cloud, the only editor. Older systems also offer the Class Builder transaction SE24, Class Builder, which creates the same objects.

A class always has two parts that you write one after the other. The definition lists the components and says who may use them; the implementation contains the code of the methods. Both are required, and the definition must come first in a local class.

flowchart LR A[Class definition: the list of components] --> B[Class implementation: the method bodies] A --> C{Visibility section} C --> D[PUBLIC: everyone] C --> E[PROTECTED: the class and its subclasses] C --> F[PRIVATE: the class only, and its friends]

The next listing is the global class of the running example. It is complete and compiles as it stands; the sections below explain each line. It runs in the local playground together with the program in the next section.

CLASS zcl_exp_claim_validator DEFINITION PUBLIC FINAL CREATE PUBLIC.

  PUBLIC SECTION.
    TYPES ty_amount TYPE p LENGTH 8 DECIMALS 2.

    CONSTANTS max_amount TYPE ty_amount VALUE '500.00'.

    CLASS-METHODS class_constructor.

    METHODS constructor
      IMPORTING limit TYPE ty_amount DEFAULT zcl_exp_claim_validator=>max_amount.

    METHODS is_valid
      IMPORTING amount        TYPE ty_amount
      RETURNING VALUE(result) TYPE abap_bool.

    METHODS check
      IMPORTING amount TYPE ty_amount
      EXPORTING ok     TYPE abap_bool
                reason TYPE string.

    METHODS cap
      CHANGING amount TYPE ty_amount.

    CLASS-METHODS instance_count
      RETURNING VALUE(result) TYPE i.

  PROTECTED SECTION.
    DATA checked TYPE i.

  PRIVATE SECTION.
    CLASS-DATA instances TYPE i.
    DATA limit TYPE ty_amount.
ENDCLASS.

CLASS zcl_exp_claim_validator IMPLEMENTATION.
  METHOD class_constructor.
    instances = 0.
  ENDMETHOD.

  METHOD constructor.
    me->limit = limit.
    instances = instances + 1.
  ENDMETHOD.

  METHOD is_valid.
    checked = checked + 1.
    result = xsdbool( amount > 0 AND amount <= limit ).
  ENDMETHOD.

  METHOD check.
    ok = is_valid( amount ).
    IF ok = abap_true.
      reason = `within the limit`.
    ELSEIF amount <= 0.
      reason = `amount must be positive`.
    ELSE.
      reason = |above the limit of { limit }|.
    ENDIF.
  ENDMETHOD.

  METHOD cap.
    IF amount > limit.
      amount = limit.
    ENDIF.
  ENDMETHOD.

  METHOD instance_count.
    result = instances.
  ENDMETHOD.
ENDCLASS.

Components and visibility sections

Everything a class declares is a component: attributes, methods, constants, types, and also events and implemented interfaces, which are covered on Events and Interfaces, Inheritance and Polymorphism. The definition groups the components in up to three sections, always in this order: PUBLIC SECTION, PROTECTED SECTION, PRIVATE SECTION.

Section Who may use the components Typical content

PUBLIC SECTION

Any program or class that can see the class

The methods other code is meant to call, public constants and types: the interface of the class towards the world

PROTECTED SECTION

The class itself and its subclasses

Helpers and data that subclasses need but the outside world must not touch

PRIVATE SECTION

The class itself, and its friends

Internal data and helper methods that you want to be able to change without breaking any caller

Keeping data private and exposing only methods is called encapsulation. The reason is practical: as long as the public methods behave the same, you can change what the class stores or how it works without touching any code that uses it. In the example the limit is private, so the only way to learn it is check, which reports it inside a message.

A public attribute may be declared READ-ONLY: code outside can read it, but only the class itself and its subclasses may change it. This is the middle road for plain data that callers legitimately need to see.

Attributes: instance, static and constants

An attribute is a variable declared inside a class. There are two kinds, and the difference matters.

  • An instance attribute (declared with DATA) exists once per object. If two validators are created with different limits, each remembers its own. In the example, limit and checked are instance attributes.

  • A static attribute (declared with CLASS-DATA) exists once per class, shared by every object of that class and usable even when no object exists. In the example, instances counts how many validators have been created. A static attribute lives for the duration of one internal session (one running program context): each new run starts again from its start value.

  • A constant (declared with CONSTANTS) is a static value that never changes. A public constant, such as max_amount, is read from outside as zcl_exp_claim_validator=>max_amount without any object.

The pair of characters => selects a static component by class name, and the pair -> selects a component of an object by the name of the variable that points to it. Inside the class’s own methods you may leave out the prefix, and me-> names the current object explicitly. me->limit = limit. in the constructor uses me to tell the attribute (me->limit) from the parameter of the same name (limit).

Methods and their parameters

A method is a block of code with a name and parameters, declared with METHODS (instance method) or CLASS-METHODS (static method) in a section and written between METHOD and ENDMETHOD in the implementation. The parameters say how data moves across the call:

  • IMPORTING: a value the caller passes in. The method may read it but not change it (by default it is passed by reference, so changing it would change the caller’s variable, which ABAP forbids for importing parameters).

  • EXPORTING: a value the method sends back through a variable the caller names. Several are allowed. check in the example returns both ok and reason.

  • CHANGING: a variable the caller passes in and that the method may update, as cap does with the amount.

  • RETURNING VALUE(result): the single result of the method. It is always passed by value, and a method that has a returning parameter may not also have exporting or changing parameters. Such a functional method can be used inside an expression, for example xsdbool( ... ) or as an operand of a comparison, which makes calling code short.

Parameters may be marked OPTIONAL (the caller may leave them out; the parameter is then initial) or given a DEFAULT value (used when left out, as limit in the constructor). VALUE(name) instead of plain name passes by value, which copies the data in and, for an exporting or changing parameter, copies it back only when the method ends normally.

The call syntax is the same for instance and static methods apart from how the method is named:

result = validator->is_valid( 120 ).
validator->check( EXPORTING amount = 900 IMPORTING ok = ok reason = reason ).
validator->cap( CHANGING amount = claim_amount ).
count = zcl_exp_claim_validator=>instance_count( ).

When a method has exactly one importing parameter and no others, you may write the value without the name, as in is_valid( 120 ); with several parameters, always name them. An instance method can use both instance and static attributes. A static method belongs to the class and has no object behind it, so it may use only static attributes. The transpiler of the local playground reports the mistake of using an instance attribute in a static method like this:

Error: check_syntax, "total" not found, Target, zoo_bad2.prog.abap:9

The message names the statement total = 0. inside CLASS-METHODS reset, where total was declared with DATA; the real ABAP compiler words it differently but rejects the same statement.

Creating objects and reference variables

A class by itself does nothing; you create an object from it. The variable that holds the object is a reference variable, declared with TYPE REF TO and a class name. It does not contain the object but points to it, like a street address points to a house. NEW class( ) creates an object and returns a reference to it, and the call of the constructor happens as part of it:

DATA(validator) = NEW zcl_exp_claim_validator( ).
DATA(strict)    = NEW zcl_exp_claim_validator( limit = 100 ).

When the reference variable was declared earlier with a type, NEW #( ) takes the class from that type and avoids repeating its name. The old form CREATE OBJECT validator EXPORTING limit = 100. does the same and is still seen in legacy code.

Because a variable holds a reference, assigning it to another variable copies the address, not the object. After DATA(c3) = c1. both names lead to the same object, and a change through one is visible through the other. The next listing is a program that uses the class above and a small local class lcl_counter to show that, and that instance attributes belong to the object while a static attribute is shared. It was run in the local playground (the open-abap transpiler with the class of the previous listings in the same package); the program uses WRITE for output, which ABAP Cloud does not offer.

REPORT zoo_demo.

CLASS lcl_counter DEFINITION FINAL.
  PUBLIC SECTION.
    CLASS-DATA created TYPE i READ-ONLY.
    DATA value TYPE i READ-ONLY.
    METHODS constructor IMPORTING start TYPE i DEFAULT 0.
    METHODS increment.
ENDCLASS.

CLASS lcl_counter IMPLEMENTATION.
  METHOD constructor.
    value = start.
    created = created + 1.
  ENDMETHOD.
  METHOD increment.
    value = value + 1.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA(validator) = NEW zcl_exp_claim_validator( ).
  WRITE / |120.00 valid: { validator->is_valid( 120 ) }|.
  WRITE / |900.00 valid: { validator->is_valid( 900 ) }|.

  DATA ok TYPE abap_bool.
  DATA reason TYPE string.
  validator->check( EXPORTING amount = 900 IMPORTING ok = ok reason = reason ).
  WRITE / |check 900: { ok } / { reason }|.
  validator->check( EXPORTING amount = -5 IMPORTING ok = ok reason = reason ).
  WRITE / |check -5: { ok } / { reason }|.

  DATA claim_amount TYPE zcl_exp_claim_validator=>ty_amount VALUE '750.00'.
  validator->cap( CHANGING amount = claim_amount ).
  WRITE / |capped: { claim_amount }|.

  DATA(strict) = NEW zcl_exp_claim_validator( limit = 100 ).
  WRITE / |strict 120: { strict->is_valid( 120 ) }|.
  WRITE / |validators created: { zcl_exp_claim_validator=>instance_count( ) }|.
  WRITE / |limit constant: { zcl_exp_claim_validator=>max_amount }|.

  DATA(c1) = NEW lcl_counter( ).
  DATA(c2) = NEW lcl_counter( 10 ).
  c1->increment( ).
  c1->increment( ).
  c2->increment( ).
  WRITE / |c1: { c1->value }, c2: { c2->value }, created: { lcl_counter=>created }|.

  DATA(c3) = c1.
  c3->increment( ).
  WRITE / |c1 after c3 increment: { c1->value }|.

Output of the run:

120.00 valid: X
900.00 valid:
check 900:  / above the limit of 500.00
check -5:  / amount must be positive
capped: 500.00
strict 120:
validators created: 2
limit constant: 500.00
c1: 2, c2: 11, created: 2
c1 after c3 increment: 3

The type abap_bool has the two values abap_true, shown as X, and abap_false, shown as a blank, which is why the failing lines print nothing after the colon. The two validators have different limits (500.00 and 100) and the shared counter reports 2; c1 and c2 keep their own values, while created counts both.

A reference variable that has not been given an object is initial. Calling a method through it raises the catchable exception CX_SY_REF_IS_INITIAL, one of the most common runtime errors of newcomers. Test with IS BOUND first when a reference may be empty. The playground cannot reproduce this error (the transpiled program stops with a JavaScript error instead), so the following listing requires an SAP system; not run here.

DATA validator TYPE REF TO zcl_exp_claim_validator.

TRY.
    DATA(ok) = validator->is_valid( 10 ).
  CATCH cx_sy_ref_is_initial.
    " the reference was not bound to an object yet
    validator = NEW #( ).
ENDTRY.

IF validator IS BOUND.
  ok = validator->is_valid( 10 ).
ENDIF.

An object is removed automatically by the garbage collector once nothing points to it any more. There is no statement to delete an object; clearing or overwriting the last reference is enough.

Constructors

A constructor sets something up at the right moment, so that nobody can use it half-prepared. ABAP has two kinds.

  • The instance constructor, the method named constructor, runs once for every object, as part of NEW or CREATE OBJECT. It may have importing parameters (the arguments written in the NEW call) and may raise exceptions. In the example it stores the limit and counts the object. In a subclass the constructor must call the constructor of the superclass before it uses any instance component; inheritance is covered on Interfaces, Inheritance and Polymorphism.

  • The static constructor, the method named class_constructor, is declared with CLASS-METHODS, takes no parameters and runs once per class and internal session, automatically, before the class is used for the first time (before the first object is created, or a static component is accessed). It initialises static attributes. The instances = 0. in the example is only illustrative: static attributes of type i start at 0 anyway.

flowchart TD A[First use of the class in the program] --> B[class_constructor runs once] B --> C[NEW class: constructor runs for the new object] C --> D[Methods are called on the object] D --> E[Last reference removed: garbage collector frees the object]

FINAL, CREATE and friends

Two additions on the first line of the definition control how a class may be used.

  • FINAL means nobody can inherit from the class. A method may also be FINAL, meaning subclasses cannot redefine it. Make a class final unless you have designed it for inheritance: a final class can be changed freely inside, because nobody has subclassed it.

  • CREATE PUBLIC, CREATE PROTECTED and CREATE PRIVATE decide who may create objects with NEW. CREATE PRIVATE makes the class a gatekeeper: only the class itself (typically in a static method, the factory method) and its friends can create objects.

A class can name friends with FRIENDS. A friend may see the private and protected components and, when the class is CREATE PRIVATE, may create objects. Friendship is granted by the owner and goes one way: naming a friend does not make the owner a friend of that class. The most common friend is the ABAP Unit test class of the class under test, which gets access to the internals in order to test them. The listing below shows both: a policy class that nobody can create directly, a static method that does the creation, and a friend that reads the private component. It was run in the local playground.

REPORT zoo_friends.

CLASS lcl_factory DEFINITION DEFERRED.

CLASS lcl_policy DEFINITION FINAL CREATE PRIVATE FRIENDS lcl_factory.
  PUBLIC SECTION.
    CLASS-METHODS standard RETURNING VALUE(result) TYPE REF TO lcl_policy.
    DATA limit TYPE i READ-ONLY.
  PRIVATE SECTION.
    DATA secret_code TYPE string VALUE `internal`.
ENDCLASS.

CLASS lcl_policy IMPLEMENTATION.
  METHOD standard.
    result = NEW #( ).
    result->limit = 500.
  ENDMETHOD.
ENDCLASS.

CLASS lcl_factory DEFINITION FINAL.
  PUBLIC SECTION.
    CLASS-METHODS strict RETURNING VALUE(result) TYPE REF TO lcl_policy.
    CLASS-METHODS secret_of IMPORTING policy TYPE REF TO lcl_policy RETURNING VALUE(result) TYPE string.
ENDCLASS.

CLASS lcl_factory IMPLEMENTATION.
  METHOD strict.
    result = NEW #( ).
    result->limit = 100.
  ENDMETHOD.
  METHOD secret_of.
    result = policy->secret_code.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA(p1) = lcl_policy=>standard( ).
  DATA(p2) = lcl_factory=>strict( ).
  WRITE / |standard: { p1->limit }, strict: { p2->limit }|.
  WRITE / |friend reads: { lcl_factory=>secret_of( p1 ) }|.

Output of the run:

standard: 500, strict: 100
friend reads: internal

A NEW lcl_policy( ) anywhere outside the class and its friend is rejected when the program is checked. The playground reports it as:

Error: check_syntax, lcl_p cannot be instantiated, class is defined as private, zoo_bad.prog.abap:11

The message comes from a program with a private class named lcl_p; the real compiler words it differently but refuses the statement in the same place.

What older books show, and what has changed

The first edition of the ABAP Objects book (2002) and many pages and systems written before ABAP 7.40 show a different style. Knowing it lets you read legacy code, and the current form is what you should write.

  • Objects were created with CREATE OBJECT ref EXPORTING ... after declaring DATA ref TYPE REF TO class. The current form is NEW class( ... ) with an inline DATA( ).

  • Methods were called with CALL METHOD obj->method EXPORTING a = 1 IMPORTING b = x. The functional call obj->method( a = 1 ) is shorter and is the form that works in expressions; CALL METHOD is obsolete.

  • Class-related exceptions were often declared as classic EXCEPTIONS after the parameters; class-based exceptions replace them (see the page on exceptions).

  • Classes were created in the Class Builder (SE24) and edited in SE80 or SE38. ADT in Eclipse is the strategic tool and the only one for ABAP Cloud.

  • Global classes in older systems may use header lines, TABLES work areas or WRITE output; none of them is allowed in a class that must pass the ABAP Cloud check.

Common mistakes

  • Declaring a method in the definition and forgetting its METHOD ... ENDMETHOD block in the implementation (or the reverse): the class does not compile.

  • Putting the sections out of order. They must read public, protected, private.

  • Using an instance attribute in a static method (shown above).

  • Calling an instance method with the class name, as in zcl_exp_claim_validator=>is_valid( 1 ). Use an object.

  • Making every attribute public. Anything public is a promise to every caller; keep data private and expose methods.

  • Calling a method through a reference that is not bound to an object (CX_SY_REF_IS_INITIAL).

Summary

  • A class defines attributes and methods; an object is one instance of a class created with NEW.

  • A local class is visible only in its program or class pool; a global class is part of the repository and usable everywhere. You write global classes in ADT.

  • The definition lists components in the public, protected and private sections, in that order; the implementation holds the method bodies.

  • Instance attributes belong to each object, static attributes (CLASS-DATA) and constants are shared; a static method can only use static attributes.

  • Parameters are IMPORTING, EXPORTING, CHANGING and a single RETURNING VALUE(...); a method with RETURNING is a functional method that can be used inside expressions.

  • constructor runs per object, class_constructor once per class and internal session; FINAL, CREATE PRIVATE and FRIENDS control inheritance, creation and access.

  • Reference variables point to objects; assigning copies the pointer, and an unbound reference raises CX_SY_REF_IS_INITIAL when used.

Try it

To do this by hand, follow the guide Classes, Interfaces and Exceptions: it builds a claim validator class, a payout interface and an exception class.