SAP Tech Pro

SAP Technical Blog
Topprice Price Comparison

Object Oriented Programming in ABAP - Static methods can only use static attributes, instance methods use both

Object Oriented Programming in ABAP - Static methods can only use static attributes, instance methods use both

Static methods of a class can only use static attributes of that class. It cannot use instance attributes. But, instance methods can use both.

 

The following program contains a class C1 which contains the following:-

Component Type    Static/Instance
stnum    Data    Static
Instnum    Data    Instance
Stmeth    Method    Static
Instmeth    Method    Instance

 

 

Both the static and instance methods are attempting to display values of the static and instance attributes: STNUM and INSTNUM .

On compilation, an error will be generated which will demonstrate that static method STMETH cannot work with instance attribute, INSTNUM.

 



REPORT zstp_oo_abap.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
    CLASS-DATA : stnum TYPE i VALUE 5.
    DATA : instnum TYPE i VALUE 6 .
    CLASS-METHODS : stmeth .
    METHODS : instmeth .
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD : stmeth .
    WRITE:/5 stnum .
    WRITE:/5 instnum .  " TO BE DELETED
  ENDMETHOD.

  METHOD instmeth.
    WRITE:/5 stnum .
    WRITE:/5 instnum .
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA : oref1 TYPE REF TO c1.
  CALL METHOD c1=>stmeth .
  CREATE OBJECT oref1.
  CALL METHOD oref1->instmeth.


You will get syntax error -

image

 

Comment the line - WRITE:/5 instnum .  " TO BE DELETED

and the program gets complied and you the output is displayed as below

image

Add comment

Before Buying, Compare Prices at Topprice.in

Topprice.in