Tuesday, June 23, 2009

Inheritance and Instantiation

If you instantiate a subclass, you instantiate all the superclasses at the same time, whereby the initialization of superclass attributes is ensured by the call of the superclass constructors, as described in Inheritance and Constructors.

For each individual class, the CREATE PUBLIC|PROTECTED|PRIVATE additions to the CLASS statement control who can create an instance of the class or, in other words, can call its instance constructor.

The effects of this is are:

If you defined a superclass in a path of the inheritance tree using the CREATE PRIVATEaddition, outside users cannot instantiate a subclass, and a subclass cannot even instantiate itself, because it has no access to the instance constructor of the superclass.

It would be useful, therefore, also to apply the FINAL addition to a class that was defined using the CREATE PRIVATE addition, in order to prevent a derivation of subclasses. Otherwise subclasses of such superclasses have the implicit CREATE NONE addition.

The only exception to this rule is if a superclass that can be privately instantiated offers its friendship to its subclasses. The direct route is rarely the case here because the superclass must know its subclasses in order for it to be possible. However, a superclass can also offer friendship to an interface which, in turn, can be implemented by its subclasses.

Conversely, you cannot create objects of subclasses in their superclass, if these are declared using CREATE PROTECTED or CREATE PRIVATE, unless they are friends of its subclasses.

Possible Cases

Superclass with no addition or CREATE PUBLIC

Whether they are friends of the superclass or not, subclasses can have every CREATE addition. Without addition they inherit the attribute CREATE PUBLIC. The superclass instance constructor is visible to everyone. The subclass controls the visibility of its own instance constructor, independently of the superclass.

Superclass with CREATE PROTECTED addition.

Whether they are friends of the superclass or not, subclasses can have every CREATE addition. Without addition they inherit the attribute CREATE PROTECTED. The superclass allows its subclasses unlimited instantiation and therefore also the publishing of its protected instance constructor.

Superclass with CREATE PRIVATE addition

Subclass no friend of the superclass

The subclass has the implicit addition CREATE NONE. Since nobody other than the superclass itself can call its instance constructor, the subclass cannot be instantiated. None of the CREATE additions is permitted since this would always lead to the unauthorized publishing of the superclass constructor.

Subclass is friend of the superclass

If the subclass has no addition, it inherits the attribute CREATE PRIVATE. However, all CREATE additions are permitted. As a friend, the subclass can publish the superclass' private constructor in any form.

No comments:

Blog Archive