• Articles
  • Tutorials
  • Interview Questions
  • Webinars

Downcasting in Java - Learn How to Access the Inherited Methods and Variables of a Parent Class

Downcasting in Java

When child class refers to the object of Parent class then it is known as downcasting. If you perform it directly then it gives compilation error so typecasting is used to perform downcasting but ClassCastException is thrown at runtime.
e.g.

class Flower {
}
class Rose extends Flower {
static void smell(Flower f) {
Rose r = (Rose) f; //downcasting using typecasting
System.out.println("Downcasting is performed");
}
public static void main (String [] args) {
Flower f=new Rose();
Rose.smell(f);
}
}

Output
Downcasting is performed

Want to ace your next Java interview? Check out our recent blog post about the most common Java interview questions and answers!

instanceof Operator in Java –

Using instanceof operator you can test the object is an instance of specific class type or not.  That means you can compare instance with particular type. It returns true or false. So it is also a comparison operator.

e.g.

class Intellipaat{
public static void main(String args[]){
Intellipaat in=new Intellipaat();
System.out.println(in instanceof Intellipaat); /* It returns true because object i is an instance of class Intellipaat */
}
}

Output
true

Learn Java

Downcasting with instanceof Operator in Java

Downcasting is performed using instanceof operator without throwing any exception.

e.g.

class Flower {
}
public class Rose extends Flower {
static void smell(Flower f) {
if(f instanceof Rose ){
Rose r=(Rose)f; //downcasting
System.out.println("Downcasting is perfromed with instanceof operator");
}
}
public static void main (String [] args) {
Flower f=new Rose();
Rose.smell(f);
}
}

Output
Downcasting is perfromed with instanceof operator

Course Schedule

Name Date Details
Python Course 20 Jul 2024(Sat-Sun) Weekend Batch
View Details
Python Course 27 Jul 2024(Sat-Sun) Weekend Batch
View Details
Python Course 03 Aug 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Senior Consultant Analytics & Data Science

Presenting Sahil Mattoo, a Senior Consultant Analytics & Data Science at Eli Lilly and Company is an accomplished professional with 14 years of experience across data science, analytics, and technical leadership domains, demonstrates a remarkable ability to drive business insights. Sahil holds a Post Graduate Program in Business Analytics and Business Intelligence from Great Lakes Institute of Management.