Casting

From Abap2Java

Jump to: navigation, search

Contents

ABAP

Implicit Casting (Widening Cast)

Primitive Data Types

Implicit casting takes places, when converting from a type to a broader type. No loss of information is possible.

DATA b TYPE INT2.
DATA i TYPE INT4.
i = b. "widening cast

Objects

Objects can only be casted implicitly to the objects they inherit from.

DATA lr_car TYPE cl_car.
DATA lr_porsche TYPE cl_porsche. "cl_porsche ingerits from cl_car
lr_porsche = get_me_a_porsche( );
lr_car = lr_porsche. "widening cast

Explicit Casting (Narrowing Cast)

Primitive Data Types

Even when casting from a bigger data type to a smaller primitive data type (so even if loss of data is possible), ABAP does not require an explicit cast operator.

DATA b TYPE INT2.
DATA i TYPE INT4.
b = i. "narrowing cast

Objects

A narrowing cast from an object to another oject of an inheriting class is done using the casting operator.

DATA lr_car TYPE cl_car.
DATA lr_porsche TYPE cl_porsche. "cl_porsche ingerits from cl_car
lr_car = get_me_a_porsche( );
lr_porsche ?= lr_car. "narrowing cast

See also:
Data Type, OO, INHERITING, class, WRITE TO

Java

Since Java has several datatypes as well as individual types, the conversation from one to another requires casting.

Implicit Casting

Primitive Data Types

Implicit casting takes places, when converting from a type to a broader type. No loss of information is possible.

byte b = 7;
int i = b;

Casting is neither possible from nor to a boolean. Casting to char always expects an explicit cast.

Objects

Since every class extends from the class Object implicit casting is possible as well. Generally objects can only be casted implicitly to the objects they extend from. (including implements)

Object o = new Vector();

Explicit Casting

Primitive Data Types

If loss of information is possible through casting, Java expects an explicit cast.

int i = 12;
byte b = (byte) i;

Objects

A class can only be casted explicitly to its descendants. Otherwise a java.lang.ClassCastException is throughn.

class A {}
class B extends A {}
class C {}

B b = new A();     // compile time error - an explicit cast expected
B b = (B) new A(); // compiles, but will fail at runtime 
A a = new B(); // good
A a = (A) new B(); // still good, but explicit cast is not needed

C c = (C) new B()  // compiles, fails at runtime with java.lang.ClassCastException

See also:
Data type, OO, Extends, class

Personal tools