Downcasting

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 –

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 

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
Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

Course Schedule

Name Date Details
Python Course 01 Apr 2023(Sat-Sun) Weekend Batch
View Details
Python Course 08 Apr 2023(Sat-Sun) Weekend Batch
View Details
Python Course 15 Apr 2023(Sat-Sun) Weekend Batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *