gram77
gram77

Reputation: 531

"Statement is not accessible" error after declaration of local classes

The following ABAP program throws error Statement is not accessible. The program contains an interface, and two classes: c2 inherited from c1. Error is thrown in statement CREATE OBJECT cref1.

REPORT  z_upcast_downcast_objref.
INTERFACE i1.
  DATA a1 TYPE i.
ENDINTERFACE.                    "i1

INTERFACE i2.
  INTERFACES i1.
  ALIASES a1 FOR i1~a1.
  DATA a2 TYPE i.
ENDINTERFACE.                    "i2

CLASS c1 DEFINITION.
  PUBLIC SECTION.
    INTERFACES i2.
ENDCLASS.                    "c1 DEFINITION

CLASS c2 DEFINITION INHERITING FROM c1.
  PUBLIC SECTION.
    METHODS m1.
ENDCLASS.                    "c2 DEFINITION

CLASS c2 IMPLEMENTATION.
  METHOD m1.
    WRITE : / 'In c2->m1 method'.
  ENDMETHOD.                    "c2
ENDCLASS.                    "c2 DEFINITION

DATA: iref TYPE REF TO i2,
      cref1 TYPE REF TO c1,
      cref2 TYPE REF TO c2.

CREATE OBJECT cref1.

TRY.
    cref2 ?= iref.
    CALL METHOD cref2->('M1').
  CATCH cx_sy_move_cast_error
        cx_sy_dyn_call_illegal_method.
ENDTRY.

Upvotes: 6

Views: 12420

Answers (1)

Suncatcher
Suncatcher

Reputation: 10621

The compiler notifies you that it cannot execute CREATE OBJECT statement because it is not assigned to implicit START-OF-SELECTION block. You have 2 options here:

  1. Assign it to explicit START-OF-SELECTION block by putting this line before creating object

    ...
    START-OF-SELECTION.
    
    CREATE OBJECT cref1.
    ...
    
  2. Place implementation of your c2 class to the end of the report.

Addition: By the way, you raised an interesting question I wasn't aware of. I found a bunch of reports about this problem on SCN (1,2,3) where folks proposed the right solution but nobody could explain it confidently, in an evidence-based and well-argued manner. But finally I can do it:)
In spite of well-known fact that all non-declarative statement are assigned to implicit SOS event (if no other events are declared), this is not the point when we declare local classes, and here is how it is explained by SAP:

The position of the implementation part in the source code is thus unimportant. For clarity, however, you should either put all the implementation parts of local classes at the end of the program, or directly after the relevant definition part. If you do the latter, note that you must then assign subsequent non-declarative statements explicitly to a processing block such as START-OF-SELECTION, so that they can be accessed.

Upvotes: 11

Related Questions