Encapsulation is an Object Oriented Programming (OOP) concept that binds together data and functions that manipulate the data, and keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Encapsulation is a mechanism of bundling the data and the functions that use them, and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
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
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
Report ZEncap1.
Interface inter_1.
Data text1 Type char35.
Methods method1.
EndInterface.
CLASS Class1 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class2 Definition.
PUBLIC Section.
Interfaces inter_1.
ENDCLASS.
CLASS Class1 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 1 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
CLASS Class2 Implementation.
Method inter_1~method1.
inter_1~text1 = 'Class 2 Interface method'.
Write / inter_1~text1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: Object1 Type Ref To Class1, Object2 Type Ref To Class2.
Create Object: Object1, Object2.
CALL Method: Object1->inter_1~method1, Object2->inter_1~method1.
The above code produces the following output:
Class 1 Interface method
Class 2 Interface method
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.
No comments:
Post a Comment