Type Casting in ABAP Class

Note: If you are searching for basic type casting/conversion of ABAP variable in Reports/Program, click here.

Prerequisite:

1. You must have a basic Idea of local class and instance/reference of class.

2. Inheritance and Polymorphism concept

Note: Parent Class is also called base class and Child class is also called Sub class.

What is Static and Dynamic Type?

Before we talk about type casting, we need to know what are static Type and Dynamic type. Each reference variable has a dynamic type and a static type.

Suppose we have a class C1 and its child class C2.

So, in our program we will write following code to make reference and create object.

DATA: obj1 TYPE REF TO C1.

Here obj1 is our reference variable and C1 is the Static Type.

Thus anything that comes after TYPE REF TO is a static type because the object obj1 is pointing to fixed or static type [here class C1].

Now, in our code, we proceed as below:

CREATE OBJECT obj1.

In this line we actually point to the class C1 using our object obj1. This pointing is called Dynamic Type and it is pointing to C1 same as the static type above.

We can also write following code:

CREATE OBJETC obj1 TYPE C2.

In this line we are pointing to child class C2 of C1. This pointing is defined at runtime and called as Dynamic Type, and this time it is not same as the static type.

Thus we conclude that Dynamic type is defined at runtime of the program while static type is declared with the declaration of reference variable. Static type can be same as Dynamic type or less specific than it [it means, it can just point to the parents and not all the child unlike the dynamic type which can].

What is a Type casting?

Type Casting in ABAP is just like casting in other computer languages. It is one way of inheriting the properties from either base/parent class or sub/child class into one another. It is used to cast one data type, class or Interface into another data type, class or interface.

For data type casting, refer here.

Definition:

Type casting is a process of converting reference of class or interface to another, given both the class are from same hierarchy i.e. either one of them must be a parent class and the other a child class.

Syntax:

Destination_Ref = | ?= Source_Ref.

Why we need Type casting?

How to achieve a type casting?

Example

What are types of Type Casting?

Some Basic rules of type casting.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Translate »