38 - SAP ABAP - Encapsulation
38 - SAP ABAP - Encapsulation
ABAP supports the properties of encapsulation and data hiding through the creation of
user-defined types called classes. As discussed earlier, a class can contain private,
protected and public members. By default, all items defined in a class are private.
Encapsulation by Interface
Encapsulation actually means one attribute and method could be modified in different
classes. Hence data and method can have different form and logic that can be hidden to
separate class.
Let's consider encapsulation by interface. Interface is used when we need to create one
method with different functionality in different classes. Here the name of the method
need not be changed. The same method will have to be implemented in different class
implementations.
Example
The following program contains an Interface inter_1. We have declared attribute and a
method method1. We have also defined two classes like Class1 and Class2. So we have
to implement the method ‘method1’ in both of the class implementations. We have
implemented the method ‘method1’ differently in different classes. In the start-
ofselection, we create two objects Object1 and Object2 for two classes. Then, we call the
method by different objects to get the function declared in separate classes.
Report ZEncap1.
Interface inter_1.
Data text1 Type char35.
Methods method1.
EndInterface.
https://www.tutorialspoint.com/sap_abap/sap_abap_encapsulation.htm 1/3
Page 2 of 3
Start-Of-Selection.
Data: Object1 Type Ref To Class1,
Object2 Type Ref To Class2.
Encapsulated classes do not have a lot of dependencies on the outside world. Moreover,
the interactions that they do have with external clients are controlled through a
stabilized public interface. That is, an encapsulated class and its clients are loosely
coupled. For the most part, classes with well-defined interfaces can be plugged into
another context. When designed correctly, encapsulated classes become reusable
software assets.
Designing Strategy
Most of us have learned through bitter experience to make class members private by
default unless we really need to expose them. That is just good encapsulation. This
https://www.tutorialspoint.com/sap_abap/sap_abap_encapsulation.htm 2/3
Page 3 of 3
wisdom is applied most frequently to data members and it also applies equally to all
members.
https://www.tutorialspoint.com/sap_abap/sap_abap_encapsulation.htm 3/3