Encapsulation and Visibility: PUBLIC, PROTECTED and PRIVATE
Learn how visibility sections protect data and keep ABAP classes maintainable.
Explanation
Encapsulation means hiding internal data and exposing only controlled behavior through methods. In ABAP classes, PUBLIC members are accessible from outside, PROTECTED members are accessible in subclasses, and PRIVATE members are accessible only inside the class. Good class design keeps attributes private and exposes meaningful methods. This prevents external programs from changing internal state unpredictably. In real SAP projects, encapsulation reduces side effects and makes debugging easier. Instead of allowing any caller to change internal values directly, the class controls changes through methods such as set_status, validate or calculate.
Code example
CLASS lcl_document DEFINITION. PUBLIC SECTION. METHODS approve. METHODS get_status RETURNING VALUE(rv_status) TYPE char10. PRIVATE SECTION. DATA mv_status TYPE char10 VALUE 'NEW'.ENDCLASS. CLASS lcl_document IMPLEMENTATION. METHOD approve. IF mv_status = 'NEW'. mv_status = 'APPROVED'. ENDIF. ENDMETHOD. METHOD get_status. rv_status = mv_status. ENDMETHOD.ENDCLASS.Real project scenario
A document status class should not expose status attribute publicly. It should provide methods like approve_document or reject_document so status changes happen only after validation.
Common mistakes
- Making all attributes public. - Allowing callers to change internal state directly. - Using getter and setter methods without business validation. - Not understanding protected visibility in inheritance.
Best practices
- Keep attributes private by default. - Expose behavior through meaningful methods. - Use protected only when subclass access is really needed. - Avoid public mutable state.
Interview angle
A strong answer should explain that encapsulation protects business rules and prevents uncontrolled changes from outside the class.