VOOZH about

URL: https://www.geeksforgeeks.org/java/class-type-casting-in-java/

⇱ Class Type Casting in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Class Type Casting in Java

Last Updated : 23 Jul, 2025

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:

  1. Upcasting is casting a subtype to a super type in an upward direction to the inheritance tree. It is an automatic procedure for which there are no efforts poured in to do so where a sub-class object is referred by a superclass reference variable. One can relate it with dynamic polymorphism.
    • Implicit casting means class typecasting done by the compiler without cast syntax.
    • Explicit casting means class typecasting done by the programmer with cast syntax.
  2. Downcasting refers to the procedure when subclass type refers to the object of the parent class is known as downcasting. If it is performed directly compiler gives an error as ClassCastException is thrown at runtime. It is only achievable with the use of instanceof operator The object which is already upcast, that object only can be performed downcast.

In order to perform class type casting we have to follow these two rules as follows:

  1. Classes must be β€œIS-A-Relationship β€œ
  2. An object must have the property of a class in which it is going to cast.

Implementation: 

(A) Upcasting

Example 1


Output
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

πŸ‘ Image

Example 2

 
 


Output
Downcasting performed

NOTE : 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'.
πŸ‘ Image


 

Example 3


 

 
 


Output
Sneha : chatting in whatsapp group
Sneha : adding a new user in whatsapp group


 

Comment