Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Rules of Downcasting Objects in Java
Next article icon

Rules of Downcasting Objects in Java

Last Updated : 11 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of downcasting for objects is discussed. It’s putting the parent’s reference variable holding the child’s object to the child’s reference variable. Downcasting cannot be implicit. The syntax of downcasting is:

Type_A ref1 = new Type_B();  Type_C ref2 = (Type_D) ref1;

In this statement, two operations are performed:

  1. converting an object referred by ref1 to type D
  2. assigning this converted object of type D to a reference variable of type C

There are 3 rules which are checked if the downcasting will be successful or not. The rules are as discussed below:

1. Check for valid conversion

For the conversion to be valid, Type A and Type D must have a relation between them. This relation can be either type A is the parent of type D, or type D is the parent of type A or type A = type D.  If there is no such relation, then there will be a compile-time error. This rule is checked by the compiler and hence it doesn't consider the type of object created in ref1 i.e it only considers type A and type D, not type B (which is the actual type of runtime object created). Considering this rule, let's see some statements which satisfy the criteria.

Object ref1 = new String();  String ref2 = (String) ref1; // satisfy rule 1  ref1 is of Object type which is parent of String    Object ref1 = new String();  Integer ref2 = (Integer) ref1 ; // satisfy rule 1  ref1 is of Object type which is parent of Integer    String ref1 = new String();  String ref2 = (String) ref1 ; // satisfy rule 1  ref1 is of String type which is same    String ref1 = new String();  String ref2 = (Object) ref1 ; // satisfy rule 1  ref1 is of String type which is child of Object     String ref1 = new String();  String ref2 = (Integer) ref1; // doesn't satisfy rule 1  ref1 is of String type which is not related to Integer   Error: incompatible types: String cannot be converted to Integer

2. Check for a valid assignment

After downcasting, the type of the object will be typed D. We know that an object can be referred to by either the same type or its parent. This leads to the second rule that the type of ref2, type C must be a parent or the same as type D. If this rule is not satisfied then the compiler will throw an error. Considering this rule, let's see some statements which satisfy the criteria.

Object ref1 = new String();  Object ref2 = (String) ref1 ; // satisfy rule 1 & rule 2  downcasted object of String type is referred by parent type Object    Object ref1 = new String();  Integer ref2 = (Integer) ref1; // satisfy rule 1 & rule 2  downcasted object of Integer type is referred by same type    Object ref1 = new String();  String ref2 = (Object) ref1; // satisfy rule 1 but not rule 2  downcasted object of Object type is referred by child class type String  Error: incompatible types: Object cannot be converted to String    String ref1 = new String();  Integer ref2 = (Integer) ref1; // doesn't satisfy rule 1 & rule 2  downcasted object of Integer type is referred by unrelated class type String  Error: incompatible types: String cannot be converted to Integer

3. Check the Compatibility of the runtime type of object

If we notice the above two points, they cover only the reference types and the converted type. The actual runtime type of the object we are trying to downcast is not yet taken into consideration. This runtime type will now be considered by JVM to check for validity. The child class object can be cast to the same class or parent class. This leads to the third runtime rule which is that type D must be a parent or same as of runtime type of ref1 i.e type B. If this condition fails, the JVM will throw ClassCastException at runtime. Considering this rule, let's see some statements which satisfy the criteria.

Object ref1 = new String();  Object ref2 = (String) ref1 ; // satisfy rule 1, rul2  & rule 3  downcasted object of String type is same as runtime type String    Object ref1 = new Integer();  Object ref2 = (Number) ref1 ; // satisfy rule 1, rul2  & rule 3  downcasted object of Number type is same parent of runtime type Integer    Object ref1 = new String();  Integer ref2 = (Integer) ref1; // satisfy rule 1, rule 2 but not rule 3  downcasted object of Integer type is not same or parent of runtime type String  Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer

Next Article
Rules of Downcasting Objects in Java

J

jainlovely450
Improve
Article Tags :
  • Java
  • Java-Object Oriented
Practice Tags :
  • Java

Similar Reads

    Upcasting Vs Downcasting in Java
    Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of typecasting for objects is discussed. Just like the data types, the objects can also be typecasted. However, in o
    3 min read
    How to swap or exchange objects in Java?
    In order to understand how to swap objects in Java, let us consider an illustration below as follows: Illustration: Let’s say we have a class called “Car” with some attributes. And we create two objects of Car, say car1 and car2, how to exchange the data of car1 and car2? Methods: Using concepts of
    5 min read
    Object Class in Java
    Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
    7 min read
    Classes and Objects in Java
    In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
    11 min read
    Understanding Classes and Objects in Java
    The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rul
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences