OOP ABAP Part 5: Instance Methods, Static Methods and Constructors
Preview · a free account unlocks the full lesson
Understand instance vs static components, the instance CONSTRUCTOR and CLASS CONSTRUCTOR, when each runs, and practical patterns such as validating objects at creation and caching customizing in static attributes.
In this lessonShow sectionsHide sections
Visual overview
Explanation
Part 1 introduced constructors briefly; this lesson looks at the instance versus static design decision in more depth. Instance components, meaning ordinary METHODS and DATA, belong to each individual object, while static components, declared with CLASS-METHODS and CLASS-DATA, belong to the class as a whole rather than to any one instance.
CONSTRUCTOR runs exactly once per CREATE OBJECT call, while CLASS_CONSTRUCTOR runs exactly once per session, before the class is used for the first time at all. Constructors exist to ensure objects start out in a valid state, or to raise an exception when they can't.
One caution worth keeping in mind: heavy reliance on static methods tends to hide dependencies and makes code harder to test.
Instance components work with the state of a particular object — its own attributes — and are called with lo_obj->method( ); each object maintains its own independent copy of its instance attributes.
Static components work differently: CLASS-DATA exists exactly once, shared across every object of the class, and CLASS-METHODS are called directly on the class, as in zcl_x=>method( ), with no object needed at all. A static method can only access static attributes directly.
This makes static components well suited to stateless helpers like conversion or formatting routines, factory methods (covered in Part 8), or caches of customizing data that only need to be read once.
Create a free account to keep reading
You have read the opening of this lesson. A free ERPClimb account unlocks the rest of it, every other lesson and topic, and your learning history, so you can pick up exactly where you stopped. No card needed.
- Full explanation
- Code example
- Real project scenario
- Common mistakes
- Best practices
- Interview angle
One tap with Google works too. Every topic keeps its first lesson open to everyone.
Keep exploring
Interview questions on this topic
Related SAP topics
Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.