ERPClimb logoERPClimb
OOP ABAP
ABAP Developmentintermediate 9 min read

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.

Key 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 this lessonShow sections

Visual overview

OOP ABAP Part 6: Encapsulation and Visibility — PUBLIC, PROTECTED, PRIVATE — learning sheetFlow: Run the code example; try to change mv_seatsocc directly from the report — syntax error → Read mv_carrid (READ-ONLY) from outside — allowed → Call set_price with a negative value and see the exception. Key ideas: THE THREE SECTIONS; WHY ENCAPSULATE; GETTERS, SETTERS AND READ-ONLY; FRIENDS. Watch out: Public writable attributes let any program put an object into an invalid state.ERPClimb.com / ABAP / LESSON 6/10 / LEARNING SHEETOOP ABAP Part 6: Encapsulation and Visibility — PUBLIC,PROTECTED, PRIVATE1 · HOW IT FLOWS1Run the code example; tryto change mv_seatsoccdirectly from the report…2Read mv_carrid(READ-ONLY) from outside— allowed3Call set_price with anegative value and seethe exception2 · KEY IDEAS EXPLAINEDThe Three SectionsPUBLIC SECTION — the class's interface to theworld. Everything here is a promise to callers;changing it can break them.PROTECTED SECTION — for subclasses: shared helpersand attributes they need.Why EncapsulateImagine seatsocc were public: any program couldset it to 500 on a 200-seat flight. With a privateattribute and a method book_seats( ), the class…Getters, Setters And Read-OnlyGetter: get_seatsocc( ) returns the value.Setter with validation: set_price( iv_price )rejects negative prices.FriendsCLASS lcl_flight DEFINITION FRIENDSltc_flight_test. — the friend class can accessprivate components. Mainly used for test classes…3 · REMEMBER · WATCH OUTRememberPUBLIC: visible to everyone; PROTECTED: the class and its subclasses;PRIVATE: only the class itself (and friends).Encapsulation = keep data private and allow changes only throughmethods that validate them.READ-ONLY public attributes allow reading without allowing changesfrom outside.!Watch outPublic writable attributes let anyprogram put an object into aninvalid state.4 · IN A REAL PROJECTA global class for sales order simulation had its item table as a public writable attribute. Two differentenhancements modified the table directly, one of them without recalculating totals, and orders were saved withinconsistent header values. The team made the table private, added methods add_item and remove_item that…Original ERPClimb learning sheet • Verify against your SAP release and edition

Expert visual walkthrough

ABAP DEVELOPMENT ACADEMY · Architecture hierarchyERPClimb.com

Encapsulation and Visibility — PUBLIC, PROTECTED, PRIVATE

OOP ABAP · Chapter-specific technical teaching map

Architecture hierarchy

1Top level

PUBLIC SECTION

2Related level

PROTECTED SECTION

3Related level

PRIVATE SECTION

4Related level

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…

Conceptual study map, not an SAP configuration screenshot or a guaranteed runtime sequence. Consult the lesson for implementation prerequisites and exceptions.

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

ABAP Code
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?

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

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.