Tuesday, June 23, 2009

Inheritance and Visibility

You cannot change the visibility area to which a component is assigned using inheritance. Component visibility affects inheritance as follows:

Public Components

The public visibility area of a subclass consists of all its own public components plus the public components of all its superclasses. From outside the class, public components are visible without restrictions.

Protected Components

The protected visibility area of a subclass consists of all its own protected components plus the protected components of all its superclasses. If the OPEN FOR PACKAGE addition is not specified, the protected area is only visible in the class itself and in all its subclasses. If the addition is specified, the protected area is also visible in the current package. If the OPEN FOR PACKAGEaddition is not specified protected seems the same as private from outside. If the addition is specified, within the current package protected has the effect of public and from outside it seems like private.

Private Components

The private visibility area of a subclass includes only the private components of this class. They are visible only in this class. The private components of superclasses cannot be used in subclasses. Only methods inherited from superclasses use (provided they have not been redefined) the private attributes of the superclass (even if the subclass has private attributes with the same name).

Example of Protected Components

Within a subnode in the inheritance tree, you can always access the protected components of superclasses. The classes affected - such as the static types of reference variables - must however be part of the inheritance tree.

In the following example, the reference variables lrefx and lref2 can see the protected components of cx in the context of the subclass c2. The static type of lref1 is c1 and is in another subnode of the inheritance tree. It cannot see any protected components of cx, in the context of c2. In a stricter model (C++ or Java), access in this example would only be possible using lref2. Access using lrefx would not be permitted, since it would involve classes (not subclasses) seeing protected components from outside. At present, ABAP extends the view of lrefx but only in a specific context. We intend, however, to introduce a stricter model and forbid access using lrefx. For this reason, you should not use this option; it causes a warning to be displayed in the extended program check.

CLASS cx DEFINITION.
PROTECTED SECTION.
METHODS mx.
ENDCLASS.

CLASS cx IMPLEMENTATION.
METHOD mx.
...
ENDMETHOD.
ENDCLASS.

CLASS c1 DEFINITION INHERITING FROM cx.
...
ENDCLASS.

CLASS c2 DEFINITION INHERITING FROM cx.
PUBLIC SECTION.
METHODS m2.
ENDCLASS.

CLASS c2 IMPLEMENTATION.
METHOD m2.
DATA: lrefx TYPE REF TO cx,
lref2 TYPE REF TO c2,
lref1 TYPE REF TO c1.
lrefx->mx( ). <--- Warning!!
lref2->mx( ).
lref1->mx( ). <--- Error!!
ENDMETHOD.
ENDCLASS.

No comments:

Blog Archive