Skip to Content
1

ABAP OO interfaces VS Class methods

Jun 14, 2017 at 02:28 PM

931

avatar image

Hi, everyone.

I've been trying to understand why and when we should use INTERFACES All the examples I've found on internet are pretty much the same. You created an interface with 2 methods. Then you implement them into a CLASS and write your code. If you create another class and implement that interface, you will have to write your code again.

So I ask: why not, instead of using INTERFACES, create 2 METHODS for each CLASS?

Can somebody help me understand the use of INTERFACES?

Look: Interface Speak. Implement in Class SpanishPerson('Hola') and EnglishPerson('Hello'). Why not a method Speak for SpanishPerson and a method Speak for EnglishPerson?

10 |10000 characters needed characters left characters exceeded
* Please Login or Register to Answer, Follow or Comment.

10 Answers

Best Answer
avatar image
Former Member Jun 14, 2017 at 08:31 PM
1

Personally I like this answer from stack overflow. It's not coded in ABAP, but the same concepts apply: https://stackoverflow.com/a/6878726

Show 7 Share
10 |10000 characters needed characters left characters exceeded

I had gone through many topics on that site but hadnt found one about interfaces. It has many explanations and examples but I still think you can use class methods in place of interfaces.

I had used the example of Speak.

Class englishPerson

method Speak()

Hi

Class spanishPerson

method Speak()

Hola

Then lets say you check the sy-langu

If Spanish then create spanishPerson, call method Speak

If English then create englishPerson, call method Speak

With interfaces

Interface Speaker

Speak

Class englishPerson

Interface Speaker, method Speak

Hi

Class spanishPerson

Interface Speaker, method Speak

Hola

Then, again, lets say you check sy-langu

If Spanish then create spanishPerson, call method Speak of interface Speaker

If English then create englishPerson, call method Speak of interface Speaker

With interface or method, we have to write code lines anyway. See? That's what I dont understand. Why interfaces if we can achieve what we want with methods of a class. But I appreciate yours and everyone elses efforts to explain interfaces to me.

I found this example: https://wiki.scn.sap.com/wiki/display/ABAP/ABAP+Objects+-+Interface+In+Local+Class+-+Real+Time+Example

He created an interface and then implemented in both classes, why not create a method which makes the same in the implemented interface in both classes?

    DATA : zcl_so_header TYPE REF TO lcl_so_header,
           zif_so_longtext TYPE REF TO lif_longtext.
MOVE zcl_so_header TO zif_so_longtext.
*******************************************
** Get Text ids for Sales Order Document **
*******************************************
 zif_so_longtext->get_textid( ). ====> why not zcl_so_header->get_textid( ) ???
0

Hmmm.... Isn't a Stuffed Crust Pizza a different object to a deep pan pizza ? And aren;t they both sub-classes of the pizza super class ???

0
Former Member
Richard Harper

I think that's what's shown there :) The author says you could have a stuffed crust prepare method and a deep pan prepare method of the class pizza or you could make a 'pizza' interface (super class) and have two subclasses implementing that interface.

0

Yes, but what I'm trying to point out is that there is no need to have an interface. You just subclass the make_Pizza class to a make_Stuffed_Crust_Pizza class and redefine the prepare method, calling the super method which mixes the dough, proves it, rolls it (cos i can't flip it like they do), and then your stuffed pizza prep. Why the need for an interface - you can't make two pizza's at the same time.

0
Former Member
Richard Harper

Hah, yeah I can't flip them either. You're correct in that there certainly are alternatives to using the interface, but in the example where you can make more than one pizza at a time, i.e. <insert your favorite delivery pizza franchise> the shown example in the link would make it beneficial. And who knows, maybe you want to implement multiple interfaces which could be another benefit as you can't do multiple inheritance.

0

Multiple inheritance may be - More than one pizza at a time ? Would you implement a 'Picks Dough Out Of Hair event' or just instantiate multiple instances of the relevant sub-classed object. And don't forget the garlic bread - a subclass of make pizza with a different topping type....

1

Multiple inheritance would be something like:

Pizza inherits from flatbread-food and cheese-topped-food.
Lasagne inherits from pasta-food and cheese-topped-food.

But as we can't do this in ABAP, we can build a cheese topper class that accepts an interface if_cheese_topped_food. It doesn't care whether it's pizza or lasagne, it just bungs the cheese on top and passes it on to the oven class.

Of course all baked foods also implement the if_baking_parameters interface for the oven class, with attributes temperature and duration, methods set_desired_doneness, events done, burnt and so on. The oven doesn't care if it's roast beef, chocolate cake, or pizza. It just interacts with the interface to do it's bit.

1
Horst Keller
Jun 16, 2017 at 07:12 AM
4

Another benefit: Testing

Imagine you want to test an event handler for a framework, e.g. an HTTP handler for ICF. During a module test there is no ICF. But you can easily create a small mock framework by implementing the ICF interfaces in own classes.

See example under https://help.sap.com/http.svc/rc/abapdocu_751_index_htm/7.51/en-US/index.htm?file=abapinterfaces_partially.htm

Share
10 |10000 characters needed characters left characters exceeded
Mike Pokraka Jun 14, 2017 at 11:33 PM
4

An interface is not so much to benefit for the one implementing it, which is what you are perfectly justified in questioning. However it is incredibly useful for the one using the object.

Think polymorphism without inheritance, or an alternative to superclasses. They are actually far more flexible than inherited classes. Without interfaces, the next developer might build another class and call his method GermanPerson.talk. An interface fixes the signature for all classes that implement a particular function.

In other words, interfaces let you abstract the class. The caller doesn't know or care if it's a German, English or Spanish person, or even a parrot for that matter. The interface zif_person ensures that the caller can tell everyone to speak.

Show 2 Share
10 |10000 characters needed characters left characters exceeded

Sorry - again I am missing the point.

Person: Super class

German, English, Spanish, Parrot Sub-class

Senegal, Grey, sub-class of parrot

How would interfaces benefit this ?

0

An 'OO Purist' principle is that interfaces are preferred to inheritance. I believe even the ABAP doco suggests this somewhere.

Inheritance automatically has a limited scope (at least in ABAP multiple inheritance is not supported), whereas you can add as many interfaces as you like to a class. Conversely, it narrows the scope of your class wherever it is used, which simplifies future change.

Here's just one simple scenario:

If you declare a superclass PERSON with an abstract method SPEAK, you can declare it as an inbound parameter for a whole load of conversation methods.

Later you want to extend the application to include parrots and aliens, both of which have a separate class hierarchy. Bummer, you need to adapt all the caller methods.

But had you implemented it with an interface, you're not tied to a class hierarchy and don't have to touch a thing.

The parrot could also implement an interface that includes a method FLY. Most birds can't speak, and with a few exceptions, generally people can't fly. With interfaces you can implement this without a problem. With inheritance your'e stuffed because a parrot can't inherit from Person and Bird at the same time. So inheritance is rigid and sequential, but interfaces let you build your own 'definition network'. What inheritance provides that interfaces cannot is the ability to define code once at the superclass and reuse it for all children. This is why we need both.

2
Horst Keller
Jun 16, 2017 at 07:19 AM
2

Question:

If you can drive one car, why can you also drive almost any other car?

Answer:

Because all cars have the same interface(s) and behave the same way independent from the vendor specific implementation.

Show 2 Share
10 |10000 characters needed characters left characters exceeded

haha....this is about the easiest, simplified explanation I have ever seen! Horst wins again!!!

1

Interface change - This is from a Ford Model - T

Image result for model t controls

You also got me thinking of one of the first cars I drove - my grandmother's c. 1954 Fiat 1100. Choke to start, optional hand crank if starter doesn't work, 4-speed column shift. floor mounted high-beam controls..

1
Jacques Nomssi Jun 14, 2017 at 03:42 PM
1

If you primarily want to reuse code, prefer composition with thin interfaces to inheritance with rich interfaces.

  1. With interface Speak, you can add a Class Parrot('Hallo') and a Class GermanPerson('Hallo').
  2. With method Speak, you will have to pretend your Parrot is a GermanPerson.

JNN

Show 3 Share
10 |10000 characters needed characters left characters exceeded

class Parrot

method Speak()

class GermanPerson

method Speak()

each method will have its own code. I understand if I implement an interface in different classes I need to write code too and they can be the same as well...I still cannot see the benefit of interface.

0
Oscar Alejandro Aranquiz Cortes

1) Interfaces can be tag interfaces with no methods.

2) You can compose a number of interfaces in a new interface. You cannot inherit from multiple classes in ABAP.

3) Prefer thin interfaces. Objects have a rich/fat interface. If method Speak( ) is only implemented in class Person, then you do not need an interface. But if object Parrot should also Speak( ) like a Person, then prefer an interface.

JNN

0

Hello Oscar,

I suggest searching the web for an explanation of the Strategy pattern. I will hope the following will make sense to you.

What is the benefit of having the same method in many classes?

Our aim is to write code that receive any object implementing a given method Speak( ) and invoke the Speak( ) method dynamically. The code should work for current an future object without change. How can we achieve that?

Inheritance: Limit the object types our code will accept to subtypes of a [Person] class that implement a method Speak( ).

Make sure [Parrot], [GermanPerson], [SpanishPerson]... are subclasses of class [Person]. Each subclass redefines method Speak( ), e.g. [SpanishPerson]->Speak( ), [GermanPerson]->Speak( ), [EnglishPerson]->Speak( ), even [Parrot]->Speak( ).

Problem: we derived [Parrot] from class of [Person] just to make it Speak( ), but if we implement a Fly( ) method, someone could derive a subclass from [Parrot] that is a [Person] that can fly. Rich public interfaces will cause inheritance problems

Composition: define an interface [Person] with a method Speak( ) and make sure our code only calls method Speak( ) of Interface [Person].

We can now implement the method Person~Speak( ) in any class that choose to implement the interface [Person] without further restrictions on the type, e.g. [SpanishPerson]->Person~Speak( ), [GermanPerson]->Person~Speak( ), [EnglishPerson]->Person~Speak( ), [Parrot]->Person~Speak( ).

Benefit: the classes do not need to have an inheritance relationship.

Defining a stable public interface is a design challenge, but using one is quite simple.

JNN

1
Sandra Rossi Jun 15, 2017 at 04:46 AM
1

Imagine you are writing code and you want to add a user exit (call a method with parameters) at some place so that other developers can add some code to change a variable how they like. So you can't create a class for this code now. The simplest way is to create an interface, and you call the method of this interface (before that, you instantiate the object by getting the name of the class via a customizing class: empty -> don't create the object/don't call the method). The day a developer wants to add some code, he will create a class which implements this interface (and enter the name of the class in the table).

This is the principle of BAdIs for instance.

Show 4 Share
10 |10000 characters needed characters left characters exceeded

Interfaces are the new Badis :) I do think your explanation with Mike Pokraka's sum it up. It is not for the original writer... it is to keep subsequent programmers out of the original program/class/method while ensuring that the original code can communicate with the new.

0

No, interfaces are not the new Badis. Sandra is presenting a use case.

Furthermore, there are use cases that are beneficial to the original programmer - I don't know about you, but I often call methods of classes I've written!

1

So the next programmer redefines the class ? Am I missing the entire point here ???

0

You may not have access to the class to redefine it. It may be marked as final and not in your development space. The class may be used directly by many transactions that would have to be retested if you touched it.

It may be that interfaces present a neater and simpler solution than subclassing.Or vice versa. I use a super class/sub classes when I want to define default behaviour. I use interfaces when I wish to assign (multiple) type information. Sometimes it even makes sense to combine the two. :-)

0
Sandra Rossi Jun 15, 2017 at 05:18 AM
1

Other example: imagine you want to improve the method ADD_ATTACHMENT of class CL_DOCUMENT_BCS, so that it's easier to add a file as attachment of a mail. Currently, the file content is passed by a horrible parameter of type table of 255 bytes, or another one of type table of 255 characters if it's a text file. Moreover, it would be better to connect directly the source of the file to the input of the method, so that the developer doesn't have to bother with reading the file, converting the type, etc.

So it's better to have only one "FILE" parameter being an instance of an interface, with method GET_FILE_CONTENT which returns a string of bytes.

In the new method of ADD_ATTACHMENT, you'll call the method GET_FILE_CONTENT of the parameter FILE to get the bytes. Later you will create one class which implements the interface and method GET_FILE_CONTENT, for reading a file from the application server. Later you will create another class for reading a file from the frontend. Etc.

Share
10 |10000 characters needed characters left characters exceeded
Matthew Billingham
Jun 16, 2017 at 05:25 AM
1

Interfaces are a way of assigning more than one type to a class. In C++ you can inherit from two super classes. You can't in ABAP. You can, however, assign one or more interfaces. Sometimes sub classing just isn't flexible enough, it depends on your needs. I use it if I have a set of related objects, but to make them all subclasses of a super class seems overly heavy.

E-g- I have a set of plug in checks. The actual checks made depend on configuration. I have a factory method that reads the configuration and returns a table of references.

DATA checks TYPE STANDARD TABLE OF REF TO zif_checks WITH EMPTY KEY.
checks = zcl_check_reader=>get_checks( for_this_config-entry). 
LOOP AT checks INTO data(check).
  LOOP AT my_data INTO data(data_entry).
    check->perform_check( data_entry ).
  ...

Now of course I could have a hierarchy of check, and do it via subclassing. But then I must implement or have a super implementation of every method, even if they don't really apply to all the sub classes. If I find I'm implemented an abstract method as "do nothing, then that's an indication that interfaces would have been better.

Ultimately, it's a programming choice. Sometimes using interfaces makes life simpler.

Share
10 |10000 characters needed characters left characters exceeded
avatar image
Former Member Jun 14, 2017 at 04:11 PM
0

You are in middle of room and someone let say a tiger attacks you.

You have no weapon.

You see on the window, a human being is out standing willing to help you.

You will shout " help me.." Give me something to hit it back.

in above statements: you asked something from man standing outside to throw something.

It can be a baseball,

it can be a rod.

it can be wood log.

It can be anything, that can help you save yourself.

What are the characteristics of that thing:

- it can be thrown from that window

- it can be tossed

- its something that you can grab & hold.

It actually doesn't matter what it throws to you..

Interface is like the same: you specify the characteristics. ( import & export Parameters) structure.

the Class that implements that interface defines if, its going to throw baseball, or rod. etc..

Thanks

Anand

Show 3 Share
10 |10000 characters needed characters left characters exceeded

All right but since you need to implement(write your code) in your class, isn't it the same to have a method with the same signature? I can only see interface works in BAdIs where everyone who implements it needs to respect the signature. Understand what I mean?

0
Former Member
Oscar Alejandro Aranquiz Cortes

1.That's one example you said is correct.

2. you forgot your hands. in above example.. your hands are capable to hold anything that is thrown, so you will define your hand of interface type, instead of specific class type.

3.If you generalize the perspective, then everything can be solved in the structured programming.

4.its just a way to divide the processes based on use, but still generalize to make it available everywhere.

0
Oscar Alejandro Aranquiz Cortes

Isn't this redefinition ?

0
Oscar Alejandro Aranquiz Cortes Jun 15, 2017 at 03:13 PM
0

I found a very good video with an example that helped me understand interfaces:

https://www.youtube.com/watch?v=su41Dg17HDI&list=PLXFymkG-_2DhQQg3dP0HWQa7TlH-0gDhz

Thank you all for helping me... I feel I have taken another step to become a real developer lol.

Is there a way to make all your answers helpful?

Show 1 Share
10 |10000 characters needed characters left characters exceeded

You can up- or downvote any answer (even on other people's questions) by clicking the arrows to the left of it. Upvoting is the new 'helpful'. Downvote if you think a response is not good.

Comments on the other hand you can only 'like', though I think this counts as the same thing.

Edit: And you can always vote on other people's questions too. e.g. I've given yours the thumbs up because it was a good question which triggered some really useful discussion that I'm sure others will also find useful in future. In searches, discussions with many positive votes will come out on top, that's the general thinking behind this platform.

0