Constructors in OOPS ABAP

 Hey Everyone, We have discussed Events in our previous part.

let’s understand about Constructors :-

Constructors :-

  • Constructor is a special type of method which is executed automatically when a object is created.
  • They can not be called using the CALL METHOD statement.
  • Constructors are methods with a predefined name.
  • Multiple CONSTRUCTOR and CLASS_CONSTRUCTOR are not allowed with in a class.

Note :- Open any class in SE24(Class Builder ) transaction code.



  • We can see there are basically two types of Constructors.

  • Click on both the constructors.

  • It will be added automatically into your method section.



    • We can see, now both the constructors are not available on the top right section indicating that, we cannot have Multiple Constructor and Class Constructors at the same time.
    • let’s differentiate both of them.

Types of Constructors :-

1. Constructor ( Instance Constructor ) :-

  1. It has only importing parameters.
    • Select Instance Constructor and click on parameters.



    • In the above diagram we can clearly see that we can only have importing parameters for Instance constructors.

  2. It can access both static and Instance attributes.
  3. It is called every time when a object is created.
  4. Used to set default value for a particular instance.

2. CLASS_CONSTRUCTOR ( Static Constructor ) :-

  1. Name of the method :- CLASS_CONSTRUCTOR
  2. It does not have any parameters.
    • Select the class constructor we and click on parameters.



    • We will get a notification message that we cannot have any parameters for our class constructor.

  3. It can access only static attributes.
  4. It is called first time when a object is created.

let’s have some implementation for both these methods so that we can understand it more clearly.

  • Step 1 :- Click on the attributes tab and let’s create two instance attributes and one static attributes.


  • Step 2 :- now click on the source code of instance constructor.


  • Step 3 :- Now go to the source code of CLASS_CONSTRUCTOR.



    • As soon as I am trying to access the instance attributes inside a class constructor, We will get a error message.


    • now, you can see it is working perfectly fine.

  • Step 4:- Go to ABAP Editor ( SE38) and create object for our class.




Executing the program :-

  • Press F8 to execute the program.


  • Now, let’s see and analysis
  • We can see clearly that our Class constructor executed before the Instance constructor and it gets executed only once.
  • However our instance constructor will be executed every time when we will create any object.

Comments

Popular posts from this blog

Understanding Different Types of SAP Function Modules: Normal, RFC, and Update

Mastering ABAP: A Step-by-Step Guide to Function Modules and Groups for Modularized Programming

Introduction to SAP