Polymorphism using interface in ABAP Objects

Go down

Polymorphism using interface in ABAP Objects

Post  Uma_ABAP on Sun Apr 01, 2012 1:27 pm


Interfaces allow you to use different classes in a uniform way using interface references .For example, interfaces that are implemented in different classes extend the public scope of each class by the same set of components.

If a class does not have any class-specific public components, the interfaces define the entire public face of the class. As we know that any no of class can implement the interface differently ,and we have seen that how we can access the components of the interface through the class objects.

But we want to have a common point of access for the different implementation of the interface methods. So how do we do that?

Well we can do that by using an interface reference; we can access the different class objects by pointing the interface reference to that class.

Code:

Let’s take an example:
INTERFACE my_infc.
METHODS: I_method.
ENDINTERFACE.
CLASS c1 DEFINITION.
PUBLIC SECTION.
INTERFACES: my_infc.
ENDCLASS.
CLASS c1 IMPLEMENTATION.
METHOD my_infc~I_method.
Write:/ ‘method for c1’.
ENDMETHOD.
ENDCLASS.

CLASS c2 DEFINITION.
PUBLIC SECTION.
INTERFACES: my_infc.
ENDCLASS.

CLASS c2 IMPLEMENTATION.
METHOD my_infc~I_method.
Write:/ ‘method for c2’.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.

DATA: iref type ref to my_infc,
C1ref type ref to c1.
C2ref type ref to c2.
CREATE OBJECT: C1ref, C2ref .
Iref = C1ref. “reference of class c1 is passed to interface reference
Iref->I_method. “method implemented in class c1 is called
Iref = C2ref. “reference of class c1 is passed to interface reference
Iref->I_method. “method implemented in class c2 is called.
********************* OUTPUT**************

method for c1
method for c2


Uma_ABAP

Posts : 56
Join date : 2012-03-31

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum