Quantcast
Channel: SCN: Message List
Viewing all articles
Browse latest Browse all 9129

Re: Determine class name used for calling a static method

$
0
0

Hi Horst,

 

OK, this is getting more interesting the more I look at it. I did a little experiment and now understand that the ABAP runtime silently substitutes the subclass reference to the implementing class. I don't think this is right, doesn't make semantic sense from a pure OO point of view, because it even bypasses the class constructor.

 

Example:

REPORT zhello.

 

CLASS lcl_super DEFINITION.

  PUBLIC SECTION.

    CLASS-METHODS say_hello.

    CLASS-METHODS class_constructor.

  PROTECTED SECTION.

    CLASS-DATA hello TYPE string.

ENDCLASS.

 

CLASS lcl_super IMPLEMENTATION.

  METHOD class_constructor.

    hello = `Hello`.

  ENDMETHOD.

  METHOD say_hello.

    WRITE hello.

  ENDMETHOD.

ENDCLASS.

 

CLASS lcl_sub DEFINITION INHERITING FROM lcl_super.

  PUBLIC SECTION.

    CLASS-METHODS class_constructor.

    CLASS-METHODS say_hello_2.

ENDCLASS.

 

CLASS lcl_sub IMPLEMENTATION.

  METHOD class_constructor.

    lcl_sub=>hello = `World`.

  ENDMETHOD.

  METHOD say_hello_2.

    WRITE lcl_sub=>hello.

  ENDMETHOD.

ENDCLASS.

 

START-OF-SELECTION.

  lcl_sub=>say_hello( ).     "Hello <-- lcl_sub class constructor not accessed!

  lcl_super=>say_hello( ).   "Hello

  lcl_sub=>say_hello_2( ).   "World <-- class constructor executed

  lcl_super=>say_hello( ).   "World (correct)

 

According to the SAP Help: "The first time you address a subclass in a program, its static constructor is executed."

This is explicitly done by the code above.

I get it that the compiler somehow remaps my reference to LCL_SUB to the class where it is defined (at least it seems like this is a compile-time thing). It explains why there is no trace to the referenced class, but on a more general level the lack of CLASS_CONSTRUCTOR call doesn't make sense from OO and from the SAP help and could catch people out.

 

Note if I remove LCL_SUPER's class constructor, I get blanks instead of 'Hello', so it isn't a sequencing thing either.

 

Regards,

Mike


Viewing all articles
Browse latest Browse all 9129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>