Monday, February 7, 2011

Demo on "Narrow Casting"

Definition: The assignment of a subclass instance to a reference variable of the type "reference to super class" is described as a narrowing cast, because you are switching from a more detailed view to a one with less detail. It is also called as up-casting.

Use of narrowing casting:

A user who is not interested in the finer points of cars, trucks, and busses (but only, for example, in the fuel consumption and tank gauge) does not need to know about them. This user only wants and needs to work with (references to) the lcl_vehicle(super class) class. However, in order to allow the user to work with cars, busses, or trucks, you generally need a narrowing cast.

Principle of narrowing casting:

  1. In narrowing casting the object which is created with reference to the sub class is assigned to the reference of type super class.
  2. Using the super class reference it is possible to access the methods from the object which are only defined at the super class.
  3. This access is also called as generic access as super class is normally called as general class.

Example:

Super class: vehicle (contains general methods)

Sub class: truck (contains more specific methods)

Here method4 is the specific for the sub class and remaining methods are inherited from the super class.

Now create the object with reference to the subclass.

  1. Declare a variable with reference to the subclass.

DATA: REF_TRUCK TYPE REF TO TRUCK.

  1. Create object with this reference.

CREATE OBJECT REF_TRUCK.

Narrowing cast:

  1. Declare a variable with reference to the super class.

DATA: REF_VEHICLE TYPE REF TO VEHICLE.

  1. Assign the object reference (REF_TRUCK) to REF_VEHICLE.

REF_VEHICLE = REF_TRUCK.

Accessing methods using super class reference.

1. By the super class reference (REF_VEHICLE) it is possible to access all the methods which are defined at the super class but the implementations are taken from the sub class.

2. If any method is redefined at the sub class then that method’s implementation which exist at the sub class is taken in to consideration.

E.g. assume that ‘method2’ is redefined at the sub class.

When this method is accessed using the super class reference

Like:

Call method REF_VEHICLE->method2.

Here we can access the implementation which exists at the sub class but not from the super class.

3. It is not possible to access the methods which only defined in the sub class using the super class reference.

E.g. Method4 is not accessed using reference REF_VEHICLE.

Call method REF_VEHICLE-> Method4.

This is wrong convention.

Demo for narrowing casting:

Go to transaction SE38.

Now execute (F8):

Result:



No comments:

Tutorials on SAP-ABAP

Adobe Interactive Forms Tutorials

Business Server Pages (BSP)

Userexits/BADIs

Web Dynpro for ABAP (Step by step procedure for web dynpro,Tutorials on Web Dynpro,)

ALV Tutorials

Blog Archive

goodsites