Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Upcasting and Downcasting in Java?
3.
Upcasting in Java
3.1.
Example of Upcasting
3.2.
Syntax of Upcasting
4.
Downcasting in Java
4.1.
Example of Downcasting
4.2.
Syntax of Downcasting
5.
Why do we need Upcasting and Downcasting in Java?
6.
Why do we use Upcasting and Downcasting in Java?
7.
Differences Between Upcasting and Downcasting in Java
8.
Frequently Asked Questions
8.1.
What will happen if we perform Downcasting without Upcasting?
8.2.
Can we use a dynamic cast for Upcasting?
8.3.
Which property is shown most when Upcasting is used?
8.4.
What is the advantage of downcasting in Java?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Upcasting and Downcasting in Java

Author Akriti Bhan
1 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

This blog will cover all the basics for typecasting and upcasting, and downcasting in Java. We will start with laying down the foundation for understanding upcasting and downcasting in Java through understanding the concept of objects and classes and the functions and variables used by them.
 

Upcasting and Downcasting in Java

Typecasting is the process of converting one data type into another according to need is known as typecasting.

What is Upcasting and Downcasting in Java?

In Java, upcasting and downcasting are casting operations used to convert object references between class hierarchies, particularly in the context of inheritance. 

Upcasting involves casting an object of a subclass to a reference variable of its superclass. This is implicit and safe because it narrows the scope of available methods and attributes, ensuring that the subclass's unique features are hidden while preserving the shared characteristics of the superclass. Upcasting is primarily used to achieve polymorphism by treating different derived classes as instances of a common base class. 

Downcasting, on the other hand, is the process of casting a reference variable of the superclass back to a more specific subclass. It's explicit and requires type casting, potentially introducing runtime errors if the reference variable does not actually refer to an instance of the subclass. Proper use of the instanceof operator is often recommended to ensure type safety during downcasting. Downcasting is used to access the specific features of a subclass that are not present in the superclass.

upcasting and downcasting

We will further look into what is upcasting and downcasting in java in detail along with examples and codes.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Upcasting in Java

As the name suggests, upcasting is basically the typecasting of the child object to the parent class object. This ensures that the user accesses the methods and variables of the parent class through the child class. It should be noted that we cannot access all the variables and methods of the child class but only some of them. Upcasting is also known as widening.

Upcasting in Java

Example of Upcasting

Let us look at a coded example of upcasting to understand the concept of upcasting and downcasting in java better.

class parent_class{  
    void print() {   /*method to print inside the parent class */
       System.out.println("Inside parent class");  
    }  
 }  
 class child_class extends parent_class {  
    void print(){  
       System.out.println("Inside child class");  
    }  
 }  
 class upcasting_cn{  
    public static void main(String args[]) {  
         
       parent_class object_1 = (parent_class) new child_class();  
       parent_class object_2 = (parent_class) new child_class();  
       parent_class object_3= new parent_class();
       object_1.print();  
       object_2.print();  
       object_3.print();
    }  
 }  

Syntax of Upcasting

Inside child class
Inside child class
Inside parent class


Practice by yourself on java online compiler.

Downcasting in Java

Downcasting refers to the typecasting of the parent object to the child class object. We can also say that this is the conversion of sub-class type to super-class type. While dealing with downcasting, we cannot use any parent class methods. Downcasting is not possible implicitly but explicitly.

Downcasting in Java

Example of Downcasting

In this part of the blog, we will explore the concept of downcasting through an example.

//Parent class  
class parent_class {  
    String n;      
    void print()  
    {  
        System.out.println("Inside Parent class");  
    }  
}    
class child_class extends parent_class {  
    String cat;  
   
    /* explicit downcasting is only possible hence we use overriding*/
    @Override  
    void print()  
    {  
        System.out.println("Inside Child");  
    }  
}    
public class downcasting_cn{  
   
    public static void main(String[] args)  
    {  
        parent_class par = new child_class();  
        par.n = "CodingNinjas";  
        child_class chil = (child_class)par;  
   
        chil.cat = "im a cat";    
        System.out.println(chil.cat);  
        chil.print();  
        System.out.println(chil.n);
    }  
}  

Syntax of Downcasting

I'm a cat
Inside child
CodingNinjas

Why do we need Upcasting and Downcasting in Java?

Upcasting and Downcasting are crucial while handling class hierarchies and object manipulation. These concepts lead to code flexibility, abstraction, and code reusability.


Here are some reasons why Upcasting and Downcasting are needed.

  • Upcasting supports polymorphism by allowing objects of derived classes to be assigned to the variables of their base class. It allows objects of different derived classes to be treated uniformly through their shared base class. 
     
  • Upcasting promotes code reusability by allowing methods to accept the base class objects as parameters. In this way, a single method can handle objects of different derived classes, avoiding code duplication and promoting code reusability.
     
  • When an object is upcasted to a base class, it loses access to its subclass methods. Downcasting helps to regain access to these subclass methods and utilize them when necessary.
     
  • Downcasting provides the capability to access interface methods that are not defined in the base class. It enables us to utilize the additional methods specific to a derived class, which are not initially available through the base class reference.

Why do we use Upcasting and Downcasting in Java?

Upcasting:


1. Simplifies Code: Upcasting allows a subclass object to be treated as if it is an instance of its superclass, simplifying code by using general types when specific types are not necessary.
2. Enables Polymorphism: It enables polymorphism by allowing a method to accept parameters of the superclass type, which can actually reference objects of any subclass types, facilitating dynamic method invocation.
3. Increases Flexibility: Upcasting increases the flexibility of code by allowing it to work with a more general type, making it easier to extend and manage.
4. Safe and Implicit: It is safe and automatic (implicit) because a subclass is always more specific than its superclass, ensuring that the upcasted object will still behave correctly.
5. Useful in Collections: Particularly useful when dealing with collections like List and Set that can hold objects of the superclass type, allowing for a mix of subclass objects within the same collection.

Downcasting:


1. Accesses Subclass-Specific Features: Downcasting is necessary to access methods or fields that are specific to the subclass type when you have a reference of the superclass.
2. Required After Upcasting: It's often used after an object has been upcasted, to regain access to the subclass-specific elements or functionalities.
3. Needs Explicit Check: Downcasting requires an explicit check (using instanceof) to avoid ClassCastException, ensuring the object actually belongs to the target subclass.
4. Enables Interface Methods: Allows objects to be cast to specific interfaces, enabling the invocation of methods defined in the interface.
5. Critical for Advanced Operations: Essential for advanced class hierarchy operations, where subclass-specific behavior needs to be invoked on objects that are currently referenced by a superclass type.

Differences Between Upcasting and Downcasting in Java

Upcasting

Downcasting

It is the conversion of the child class to the parent class.

It is the conversion of the parent class to the child class.

Only some particular methods of child class can be accessed by the user.

All the variables and methods of the classes can be accessed by the user.

Upcasting can be done implicitly or explicitly.

Downcasting can only be done explicitly.

Syntax: parent par=(parent class) new Child()

Syntax: Parent par=new Child()

Child chil=(Child)par

It is not used much in daily life.

It is used more in general than upcasting.

Frequently Asked Questions

What will happen if we perform Downcasting without Upcasting?

Performing Downcasting without Upcasting leads to compilation errors. Downcasting is only possible when an object has been upcasted to a base class. Without Upcasting, the object will not know the additional methods defined in the subclass, which would result in a compilation error.

Can we use a dynamic cast for Upcasting?

No, we can’t use a dynamic cast for Upcasting. We can implicitly do Upcasting by assigning an object of the derived class to a base class reference variable.

Which property is shown most when Upcasting is used?

When Upcasting is used, the primary property that becomes evident is polymorphism. Upcasting enables polymorphic behaviour by allowing objects of different derived classes to be treated uniformly through their shared base class.

What is the advantage of downcasting in Java?

The primary advantage of downcasting in Java is the ability to access and utilize specific methods and attributes of a subclass when needed, allowing for more precise and tailored interactions with objects in an inheritance hierarchy.

Conclusion

In this blog, we discussed everything about upcasting and downcasting in java. We discussed objects, classes, instance variables, and methods. We looked in detail at the concept of upcasting and downcasting in java with their examples. Finally, we discussed the differences between upcasting and downcasting in java in a tabular manner.

You can refer to other similar articles as well

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available.

Previous article
Factory Design Pattern in Java
Next article
Sieve Of Eratosthenes In Java
Live masterclass