Before discussing the difference between Narrow Casting and Wide Casting, let’s have a short introduction of the two.
Both the Narrow casting and Wide casting is related to Inheritance concept.
The subclasses which inherit from the parent (super) class would usually have more components than the parent class, hence the subclasses are Wide.
On the other hand, the parent (super) classes have a smaller number of components, hence the parent classes are Narrow.
In Narrow casting, an instance of the subclass is assigned to the reference of the superclass. As we are switching from a “more specific view” to a “less specific view”, it is called Narrow casting. By this assignment, only the inherited components of the subclass can be accessed using the reference of the superclass.
Steps to Narrow Cast:
i) Declare a reference variable of the superclass
DATA: lr_parent TYPE REF TO super_class.
ii) Declare a reference variable of the subclass
DATA: lr_child TYPE REF TO sub_class.
iii) Create an instance of the subclass reference
CREATE OBJECT lr_child.
iv) Assign the instance to reference of the superclass
lr_parent = lr_child.
In Wide Casting, an instance of the superclass is assigned to the instance of the subclass. As we are switching to a “more specific view” from a “less specific view”, it is called Wide Casting. By this assignment, all the inherited components and specific components of the subclass can be accessed using the instance of the subclass. The Wide Casting will always fail unless the instance of a subclass has the same type as of the instance of the superclass. So, it is required to do Narrow casting always before Wide casting.
Syntax to Wide Cast:
lr_child ?= lr_parent
Now, let’s have a look at their difference.
Difference between Narrow casting and Wide Casting
|Narrow Casting||Wide Casting|
|It means copying an instance of subclass to an instance of the super class.||It means copying an instance of the super class to an instance of sub class|
|Only inherited components of the subclass can be accessed.||Inherited, as well as specific components of the subclass, can be accessed.|
|Assigning operator is used.||Casting operator is used.|
lr_parent = lr_child
lr_child ?= lr_parent