
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Downcasting in Java
What is Downcasting?
Typecasting an object of the parent class to an object of the child class is called Downcasting in Java. We need to tell the Java compiler to perform the conversion explicitly by creating an object of the child type using a reference of the parent type. It is the opposite of upcasting, where a subclass reference is converted into a superclass reference automatically by the compiler.
Typecasting is a process in which one data type or object is converted into another. It works with primitive datatypes and reference types as well. In this article, we are going to learn about downcasting and its use with examples.
Syntax of Downcasting
The syntax to downcast an object is given below:
subClassName objectName = (subClassName) superclassReference;
Uses of Downcasting
You can use downcasting for the following purposes:
- Since Java does not allow direct access to attributes and methods of a subclass through a superclass reference, you can use downcasting to access them through object of superclass.
- When you are working with polymorphism and need to retrieve the original subclass type.
- When different object types share a common superclass type.
Example of Downcasting in Java
Let's see a practical implementation of Downcasting in Java.
class Library { void showResources() { System.out.println("Library provides various resources"); } } class Student extends Library { void borrowBooks() { System.out.println("Student borrows books from the library"); } } public class Example { public static void main(String[] args) { // Upcasting Library library = new Student(); // Type checking for Downcasting if (library instanceof Student) { // downcasting Student student = (Student) library; student.borrowBooks(); student.showResources(); } else { System.out.println("Error while Downcasting"); } } }
Output
The result of the above code is as follows:
Student borrows books from the library Library provides various resources