![]() |
VOOZH | about |
Typecasting is the assessment of the value of one primitive data type to another type. In java, there are two types of casting namely upcasting and downcasting as follows:
In order to perform class type casting we have to follow these two rules as follows:
Implementation:
(A) Upcasting
Example 1
Child show method is called
Output explanation: Here parent class object is called but referred to the child's class object. Hence, one can relate this with dynamic polymorphism or function overriding.
(B) Downcasting
π ImageExample 2
Downcasting performed
π ImageNOTE : Without perform upcast if we try to downcast , ClassCastException will be thrown.
- It is a runtime exception or unchecked exception.
- It is class, present in java.lang package.
- It can be avoided by using a operator known as 'instanceof'.
Example 3
Sneha : chatting in whatsapp group Sneha : adding a new user in whatsapp group