OOP ABAP Part 6: Encapsulation and Visibility — PUBLIC, PROTECTED, PRIVATE
Lessons are open to try during our launch period. Some advanced content may move to Pro later. AI practice limits apply separately.
Use visibility sections to protect object state: PUBLIC, PROTECTED and PRIVATE components, READ-ONLY attributes, getter/setter methods with validation, FRIENDS, and CREATE PRIVATE for controlled instantiation.
In this lessonShow sectionsHide sections
Visual overview
Expert visual walkthrough
Encapsulation and Visibility — PUBLIC, PROTECTED, PRIVATE
OOP ABAP · Chapter-specific technical teaching map
Architecture hierarchy
PUBLIC SECTION
PROTECTED SECTION
PRIVATE SECTION
Encapsulation
Tutor's chapter takeaway
Use visibility sections to protect object state: PUBLIC, PROTECTED and PRIVATE components, READ-ONLY attributes, getter/setter methods with validation, FRIENDS, and CREATE PRIVATE for controlled instantiation.
In a real project
A global class for sales order simulation had its item table as a public writable attribute. Two different enhancements modified the table directly, one of them without recalculating totals, and orders were saved with…
Watch out for
• Public writable attributes. • Setters without validation for every attribute. • Putting internal helpers into the public section. • Using PROTECTED as "almost private" in classes nobody inherits from. • Overusing FRIENDS…
The situation: a real project scenario
A global class for sales order simulation had its item table as a public writable attribute. Two different enhancements modified the table directly, one of them without recalculating totals, and orders were saved with inconsistent header values.
The team made the table private, added methods add_item and remove_item that recalculate totals, and exposed a read-only copy via get_items. The next enhancement had to use the methods, and the inconsistency disappeared.
Explanation
Parts 1-5 used the PUBLIC, PROTECTED and PRIVATE sections of a class without much thought about why they exist. This part uses them deliberately.
The three sections carry distinct meaning. The PUBLIC SECTION is the class's interface to the world — everything there is a promise to callers, and changing it can break them. The PROTECTED SECTION is for subclasses: shared helpers and attributes they need but outsiders should not see.
The PRIVATE SECTION holds implementation details, which you can change freely without affecting callers at all. PUBLIC is visible to everyone, PROTECTED to the class and its subclasses, and PRIVATE only to the class itself (and to its friends). In SE24, the Visibility column shows Public, Protected or Private for each component.
Encapsulation is the practice of keeping data private and only allowing changes through methods that validate them. To see why this matters, imagine that seatsocc were public: any program could set it to 500 on a 200-seat flight.
With a private attribute and a method like book_seats( ) instead, the class checks capacity every single time it changes, so the business rule stays in one place rather than being duplicated — or forgotten — everywhere the attribute is touched. Public writable attributes let any program put an object into an invalid state.
Getters, setters and read-only attributes give you finer control. A getter such as get_seatsocc( ) simply returns a value, while a setter with validation, such as set_price( iv_price ), can reject a negative price outright. Declaring DATA mv_carrid TYPE s_carr_id READ-ONLY in the public section makes it readable from outside the class but changeable only from inside it — useful for key attributes. READ-ONLY public attributes allow reading without allowing changes from outside. Not every attribute needs a setter; create one only for what callers are actually allowed to change.
Friendship is a further, narrower exception: CLASS lcl_flight DEFINITION FRIENDS ltc_flight_test. lets the named friend class access private components. This is mainly used for test classes, and note that friendship is not inherited by a friend's own subclasses.
Instantiation can also be controlled. CREATE PUBLIC is the default and lets anyone create objects of the class. CREATE PROTECTED restricts creation to the class and its subclasses, and CREATE PRIVATE restricts it to the class itself — typically used with a static factory method or a singleton, covered in Part 8.
Finally, declaring a class FINAL prevents it from being subclassed at all, which protects its design and makes changes to its protected components safe, since no unknown subclass can depend on them.
As an exercise, run the code example and try to change mv_seatsocc directly from the report — this should fail with a syntax error. Then read mv_carrid, which is READ-ONLY, from outside the class — this is allowed. Finally, call set_price with a negative value and observe the exception it raises. By the end, your classes should expose only what callers need and protect their internal state with validating methods.
Code example
REPORT zoop_visibility. CLASS lcl_flight DEFINITION CREATE PUBLIC. PUBLIC SECTION. DATA: mv_carrid TYPE s_carr_id READ-ONLY, " readable, not changeable outside mv_connid TYPE s_conn_id READ-ONLY. METHODS: constructor IMPORTING iv_carrid TYPE s_carr_id iv_connid TYPE s_conn_id iv_seatsmax TYPE i, book_seats IMPORTING iv_seats TYPE i RAISING zcx_flight_error, set_price IMPORTING iv_price TYPE s_price, get_seatsocc RETURNING VALUE(rv_occ) TYPE i, get_price RETURNING VALUE(rv_price) TYPE s_price. PROTECTED SECTION. DATA mv_seatsmax TYPE i. " subclasses may use it PRIVATE SECTION. DATA: mv_seatsocc TYPE i, " only via book_seats mv_price TYPE s_price. METHODS log_change IMPORTING iv_text TYPE string. " internal helperENDCLASS. CLASS lcl_flight IMPLEMENTATION. METHOD constructor. mv_carrid = iv_carrid. mv_connid = iv_connid. mv_seatsmax = iv_seatsmax. ENDMETHOD. METHOD book_seats. IF mv_seatsocc + iv_seats > mv_seatsmax. " the rule lives in ONE place RAISE EXCEPTION TYPE zcx_flight_error EXPORTING textid = zcx_flight_error=>flight_full mv_carrid = mv_carrid mv_connid = mv_connid. ENDIF. mv_seatsocc = mv_seatsocc + iv_seats. log_change( |{ iv_seats } seats booked| ). ENDMETHOD. METHOD set_price. IF iv_price < 0. RAISE EXCEPTION TYPE cx_parameter_invalid_range EXPORTING parameter = 'IV_PRICE'. " dynamic check: caller error ENDIF. mv_price = iv_price. ENDMETHOD. METHOD get_seatsocc. rv_occ = mv_seatsocc. ENDMETHOD. METHOD get_price. rv_price = mv_price. ENDMETHOD. METHOD log_change. WRITE: / mv_carrid, mv_connid, iv_text. ENDMETHOD.ENDCLASS. DATA: lo_flight TYPE REF TO lcl_flight, lv_occ TYPE i. START-OF-SELECTION. CREATE OBJECT lo_flight EXPORTING iv_carrid = 'LH' iv_connid = '0400' iv_seatsmax = 3. WRITE: / 'Carrier (read-only access):', lo_flight->mv_carrid.* lo_flight->mv_carrid = 'AA'. " syntax error: READ-ONLY* lo_flight->mv_seatsocc = 500. " syntax error: PRIVATE TRY. lo_flight->book_seats( 2 ). lo_flight->book_seats( 2 ). " exceeds capacity CATCH zcx_flight_error. WRITE: / 'Booking rejected: capacity exceeded'. ENDTRY. TRY. lo_flight->set_price( '-10' ). CATCH cx_parameter_invalid_range. WRITE: / 'Negative price rejected'. ENDTRY. lv_occ = lo_flight->get_seatsocc( ). WRITE: / 'Seats occupied:', lv_occ. * Test class access to private data:* CLASS lcl_flight DEFINITION FRIENDS ltc_flight_test.Watch out
Common mistakes
- Public writable attributes.
- Setters without validation for every attribute.
- Putting internal helpers into the public section.
- Using PROTECTED as "almost private" in classes nobody inherits from.
- Overusing FRIENDS outside test classes.
Do this
Best practices
- Keep attributes private; expose behaviour, not data.
- Use READ-ONLY for key attributes callers need to read.
- Validate in setters and business methods.
- Mark classes FINAL unless inheritance is planned.
- Keep the public section small and stable.
In the interview
Interview angle
Questions: "Explain encapsulation in ABAP", "PUBLIC vs PROTECTED vs PRIVATE?", "What is READ-ONLY?", "What are friends?"
Strong answer: visibility sections control access — public for everyone, protected for subclasses, private for the class (and friends); encapsulation keeps state private and changes it only through validating methods; READ-ONLY attributes are readable but not writable outside; FRIENDS grant private access (mainly tests); CREATE PRIVATE controls instantiation.
Practice this lesson
Quick check
0 of 3 questions attempted
Question 1 of 3
What does READ-ONLY on a public attribute mean?
Question 2 of 3
A document status must only change through valid transitions. Which design enforces this?
Question 3 of 3
Which visibility allows access only from the class itself and its subclasses?
Practise this in an interview
Answer in your own words and get instant feedback, the way an interviewer would judge it.
1A custom document class exposes its status as a public attribute, and different programs set invalid status values. How do you fix this with encapsulation?
2Explain visibility modifiers (PUBLIC, PROTECTED, PRIVATE) in ABAP OO. How do they enforce encapsulation, and what is the impact on inheritance hierarchies?
Try a related Code Lab
This published exercise covers the same SAP topic. Apply the ideas in a hands-on scenario, then return to review your answers.
Open: God class doing everything →See it in code
Each example starts from a requirement, shows the design, then the code step by step with a plain-language explanation of every part.
Was this lesson helpful?
Keep exploring
Interview questions on this topic
Related SAP topics
Referenced SAP objects
Reviewed reference pages for the objects this page mentions.
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.