Preface – This post is part of the Object Oriented ABAP series.
Table of Contents
Introduction
As we know that the principles of Object-Oriented Programming are Encapsulation, Abstraction, Inheritance and Polymorphism. Polymorphism is implemented through Interfaces. It defines the ability of a message to be displayed in many forms. It allows an interface to have multiple implementations. In this article we will discuss Interface in ABAP OOPs in detail.
Consider a real-life example; a person at the same time has many roles. A woman at the same time can have many features, she can be a mother, wife, daughter or an employee but actions are as per the situation and conditions. Similarly, an interface is an independent entity which can have many implementations to extend the scope of the classes.
Properties of Interface
- Interfaces only have method definitions. Method implementation is done in implemented classes.
- Interfaces can be used by any no of classes to extend the scope of the class.
- Each class can have its own implementation of interface methods depending upon the class functionalities.
- The declaration of interface does not include the visibility section. But in the declaration part of a class, they must be listed under Public Section.
You can create an interface in SE24. Provide the interface name, methods and its parameters and implement the interface in classes.
Definition of Interface in ABAP
Interface is an independent structure which is used in classes to enhance its functionality.
Example
Let’s pin down an example.
****interface definition****
INTERFACE zif_demo.
METHOD display.
ENDINTERFACE.
****class definition ****
CLASS zcl_demo DEFINITION.
PUBLIC SECTION.
INTERFACES zif_demo.
END CLASS.
CLASS zcl_demo1 DEFINITION.
PUBLIC SECTION.
INTERFACES zif_demo.
END CLASS.
****class implementation****
CLASS zcl_demo IMPLEMENTATION.
METHOD zif_demo~display. “Interface Method implementation
WRITE : “This is the interface method in class 1..”
END METHOD.
END CLASS.
CLASS zcl_demo1 IMPLEMENTATION.
METHOD zif_demo~display. “Interface Method implementation
WRITE : “This is the interface method in class 2..”
END METHOD.
END CLASS.
****creating class object****
START-OF-SELECTION
DATA : object_demo TYPE REF TO zcl_demo.
CREATE OBJECT object_demo.
CALL METHOD : object_demo-> zif_demo~display.
DATA : object_demo1 TYPE REF TO zcl_demo1.
CREATE OBJECT object_demo1.
CALL METHOD : object_demo1-> zif_demo1~display.
In the above example, there is one interface zif_demo defined which has only the definition part. And we have two classes zcl_demo and zcl_demo1 implementing the interface. This is how we can achieve Polymorphism through interfaces.
0 Comments