Type Casting
The process of converting one data type into another is referred to as type casting. It can be done both manually and automatically. Manual typecasting is done by the programmer, and automatic casting is done by the compiler. Widening type casting and narrowing type casting are two types of type casting.
Widening type casting
Converting a narrow data type into a wider data type is known as widening type casting. It is also called implicit conversion.
Byte==>short==>char==>int==>long==>float==>double
while doing the implicit conversion
data types should be compatible with each other
target must be larger than the source
narrowing type casting
converting into a lower data type is called narrowing type casting or explicit conversion
double==>float==>long==>int==>char==>short==>byte
Upcasting
In Java, it is possible to typecast the objects in the same way as data types. For instance, if there are two classes, the parent class extends the child class. The parent object typecast to the child object is called upcasting.
We accomplish upcasting explicitly and implicitly. Upcasting helps to access the variables and methods of the parent class easily.
Created a parent class with display method.
Created child class with a display display method, which extends the parent class
Downcasting
In downcasting a parent class reference object to the child class, it is not possible to perform downcasting implicitly in Java. Because the compiler will throw the ClassCastException. So whenever performing downcasting, it has to be done explicitly. We use downcasting when we need a code that accesses the behaviors of the child class.
Created a parent Class with print method
Created child which override the print method.
Created parent class instance with id.
Performed downcasting explicitly.
Comentarios