Conversion Casting and
Promotion
What are wrapped classes
Wrapped classes are classes that allow primitive
types to be accessed as objects.
What are the four general cases for Conversion and Casting
Conversionofprimitives
Castingofprimitives
Conversionofobjectreferences
Casting of object references
When can conversion happen
It can happen during
Assignment
Methodcall
Arithmetic promotion
What are the rules for primitive assignment and method call
conversion
A boolean can not be converted to any other type
A non Boolean can be converted to another non boolean type, if the conversion
is widening conversion
A non Boolean cannot be converted to another non boolean type, if the
conversion is narrowing conversion
What are the rules for primitive arithmetic promotion conversion
For Unary operators :
If operant is byte, short or a char it is converted to an int
If it is any other type it is not converted
For binary operands :
If one of the operands is double, the other operand is converted
to double
Else If one of the operands is float, the other operand is converted to float
Else If one of the operands is long, the other operand is converted to long
Else both the operands are converted to int
What are the rules for casting primitive types
You can cast any non Boolean type to any other
non boolean type
You cannot cast a boolean to any other type; you cannot cast any other type to
a boolean
What are the rules for object reference assignment and method call
conversion
An interface type can only be converted to an
interface type or to object. If the new type is an interface, it must be a
superinterface of the old type
A class type can be converted to a class type or to an interface type. If
converting to a class type the new type should be superclass of the old type.
If converting to an interface type new type the old class must implement the
interface
An array maybe converted to class object, to the interface cloneable, or to an
array. Only an array of object references types may be converted to an array,
and the old element type must be convertible to the new element
What are the rules for Object reference casting
Casting from Old types to Newtypes
Compile time rules
- When both Oldtypes and Newtypes are classes, one should
be subclass of the other
- When both Oldtype ad Newtype are arrays, both arrays
must contain reference types (not primitive), and it must be legal to cast
an element of Oldtype to an element of Newtype
- You can always cast between an interface and a
non-final object
Runtime rules
- If Newtype is a class. The class of the expression
being converted must be Newtype or must inherit from Newtype
- If NewType is an interface, the class of the expression
being converted must implement Newtype
No comments:
Post a Comment