OO ABAP Elements CONSTRUCTORS Constructors are methods that
OO ABAP Elements CONSTRUCTORS
Constructors are methods that are not generally called explicitly (CALL METHOD or its short form), but are called implicitly. The constructor is a special instance method in a class and is always named CONSTRUCTOR. This abbreviated term actually means the instance constructor. The constructor is automatically called at runtime with the CREATE OBJECT statement.
Constructors A constructor is necessary when, after the instantiation of a class: You need to allocate resources You need to initialize attributes You need to modify static attributes You need to send messages containing the information that a new object was created
Instance Constructors Each class can have no more than one (instance) constructor The constructor must be defined in the public area The constructor’s signature can only have importing parameters and exceptions When exceptions are raised in the constructor, instances are not created, so no main memory space is occupied Except for one exceptional case, you cannot normally call the constructor explicitly There is no destructor in ABAP Objects.
ZCL_VEHICLE: INSTANCE CONSTRUCTOR ABAP SYNTAX: CONSTRUCTOR Let’s add 3 more attributes to our ZCL_VEHICLE class: Ø Make Ø Model Ø N_of_vehicles Next, we will create an instance constructor to initialize the make, model and the color attributes of the ZCL_VEHICLE class. This constructor will also count the number of created vehicles. Open Transaction SE 24
Static Constructors The static constructor is a special static method in a class and is always named CLASS_CONSTRUCTOR. The static constructor is called automatically before the class is first accessed, but before any of the following actions are executed for the first time: • Creating an instance of this class (CREATE OBJECT) • Accessing a static attribute of this class • Calling a static method of this class • Registering an event handler method for an event in this class
Static Constructors Consider the following points when you define static constructors: Each class has no more than one static constructor The static constructor must be defined in the public area The constructor’s signature cannot have importing parameters or exceptions The static constructor cannot be called explicitly
ZCL_VEHICLE: STATIC CONSTRUCTOR ABAP SYNTAX: CLASS_CONSTRUCTOR We will create a static constructor to initialize the number of tires all vehicles must posses. Open Transaction SE 24
You can address an object itself by using the predefined reference variable ME within its instance methods. E. g. ME->GET_SPEED( ) ME->MAKE ME is required when you want to show a distinction between local data objects and instance attributes with the same name.
Practical Example LET’S TEST CLASS ZCL_VEHICLE IN AN ABAP REPORT
Source Code Ø View Source Code for ZPR_TEST_VEHICLES Ø View Source Code for ZCL_VEHICLE
- Slides: 11