MichaelB.
7/28/2018 - 10:54 AM

Call the instance constructor of the superclass

  • Subclasses will inherit the instance constructor of their superclass.
  • subclass can only see the public and protected instance attributes of its superclass - not the private attributes. Ensure private attributes of the superclass also get initialised by the superclass instance constructor. When redefining instance constructors, bear in mind:
  • You do not use the redefinition addition as with the standard method statement.
  • We change the way we redefine the parameter interface of an instance constructor.
  • We must ensure we call the instance constructor of the superclass by using the statement below for the non-optional parameters of the superclass.

If a subclass does not redefine the constructor of the superclass we must fill in non-optional input parameters defined within the superclass itself. Also, if we choose to define a completely new constructor for our subclass, we must fill in the non-optional input parameters for the subclass and then ensure we call the superclass constructor to fill in its non-optional input parameters also.

If you don't create a constructor for your subclass that means you will inherit the superclass by default, so no need to do anything. If you create a sub-class constructor you are redefining the superclass and you do have to call the superclass constructor ensuring to pass in any required parameters.

super->constructor( EXPORTING att1 = val1 att2 = val2)

*If there are no input parameters
super->constructor( )



*Practical example of using instance constructors with inheritance

CLASS ford DEFINITION.
  PUBLIC SECTION.
    METHODS constructor
      IMPORTING
        p_model TYPE string.

  PROTECTED SECTION.
    DATA model TYPE string.

ENDCLASS.

CLASS mercedes DEFINITION INHERITING FROM ford.

ENDCLASS.


CLASS audi DEFINITION INHERITING FROM mercedes.
  PUBLIC SECTION.
    METHODS constructor
      IMPORTING
        p_model  TYPE string
        p_wheels TYPE i.

  PROTECTED SECTION.
    DATA wheels TYPE i.

ENDCLASS.

* IMPLEMENTATION

CLASS ford IMPLEMENTATION.
  METHOD constructor.
    model = p_model.
  ENDMETHOD.
ENDCLASS.

CLASS audi IMPLEMENTATION.
  METHOD constructor.
    CALL METHOD super->constructor
      EXPORTING
        p_model = p_model.
    wheels = p_wheels.
  ENDMETHOD.
ENDCLASS.

* Our program starts here.

DATA: my_ford     TYPE REF TO ford,
      my_mercedes TYPE REF TO mercedes,
      my_audi     TYPE REF TO audi.

START-OF-SELECTION.

  CREATE OBJECT: my_ford       EXPORTING p_model = 'FOCUS',     " SUPERCLASS
                 my_mercedes   EXPORTING p_model = 'C-CLASS',   " SUBCLASS - NO REDEFINITION
                 my_audi       EXPORTING p_model = 'A4'         " SUBCLASS - INTERFACE REDEFINED
                                         p_wheels = 4.

ULINE.