• Articles
  • Tutorials
  • Interview Questions

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

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 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.