Skip to Content
6
Jan 12, 2014 at 03:00 AM

Why is this possible in ABAP Objects?

237 Views

So I've being doing ABAP and ABAP Objects for a while now. Then I found out that accessing a protected attribute 'externally' is possible as long as you've initiated the call from inside one of its subclass.

Is anyone else surprised by this? In other languages, I don't think this is allowed. Do you think this is a good feature? Doesn't this make code less secure?

In the code below, you can see that an instance of lcl_child tried to access the protected attribute 'name' of another instance whose type is lcl_parent - a superclass of lcl_child.

REPORT YACCESSTEST.

CLASS lcl_parent DEFINITION.

PUBLIC SECTION.

METHODS constructor

IMPORTING

p_name TYPE string.

PROTECTED SECTION.

DATA name TYPE string.

ENDCLASS.

CLASS lcl_parent IMPLEMENTATION.

METHOD Constructor.

name = p_name.

ENDMETHOD.

ENDCLASS.

CLASS lcl_child DEFINITION INHERITING FROM lcl_parent.

PUBLIC SECTION.

METHODS:

Constructor,

Test

IMPORTING p_o_parent TYPE REF TO lcl_parent.

ENDCLASS.

CLASS lcl_child IMPLEMENTATION.

METHOD Constructor.

super->Constructor( 'BABY' ).

ENDMETHOD.

METHOD Test.

" Should I be able to access this 'PUBLICLY' because

" I'm inside the subclass of lcl_parent? Note that this

" can be a different instance from me.

WRITE p_o_parent->name.

ENDMETHOD.

ENDCLASS.

DATA:

o_parent TYPE REF TO lcl_parent,

o_child TYPE REF TO lcl_child.

START-OF-SELECTION.

CREATE OBJECT o_parent EXPORTING p_name = 'MOMMY'.

CREATE OBJECT o_child.

* WRITE o_parent->name. " error. not accessible!

o_child->Test( o_parent ). " outputs 'MOMMY', why possible?!?!?!?!