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 {<br>
}<br>
class Rose extends Flower {<br>
static void smell(Flower f) {<br>
Rose r = (Rose) f; //downcasting using typecasting<br>
System.out.println("Downcasting is performed");<br>
}<br>
public static void main (String [] args) {<br>
Flower f=new Rose();<br>
Rose.smell(f);<br>
}<br>
}<br>

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{<br>
public static void main(String args[]){<br>
Intellipaat in=new Intellipaat();<br>
System.out.println(in instanceof Intellipaat); /* It returns true because object i is an instance of class Intellipaat */<br>
}<br>
}<br>

Output
true

Downcasting with instanceof Operator in Java

Downcasting is performed using instanceof operator without throwing any exception.

e.g.

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

Output
Downcasting is perfromed with instanceof operator.

Related Blogs What’s Inside
Java File I/O Explores Java File I/O for handling file operations in programs.
Final Keyword in Java Outlines the final keyword in Java for preventing class or variable changes.
Thread in Java Guides on Java threads for concurrent processing in applications.
Java Tokens Describes Java tokens as core units in programming syntax.
Hamming Distance Explains Hamming distance for analyzing binary string variations.

About the Author

Software Developer | Technical Research Analyst Lead | Full Stack & Cloud Systems

Ayaan Alam is a skilled Software Developer and Technical Research Analyst Lead with 2 years of professional experience in Java, Python, and C++. With expertise in full-stack development, system design, and cloud computing, he consistently delivers high-quality, scalable solutions. Known for producing accurate and insightful technical content, Ayaan contributes valuable knowledge to the developer community.