• Articles
  • Tutorials
  • Interview Questions

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

Tutorial Playlist

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 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 04 May 2024(Sat-Sun) Weekend Batch
View Details
Python Course 11 May 2024(Sat-Sun) Weekend Batch
View Details

Full-Stack-ad.jpg