Upcasting vs Downcasting in Java
## Upcasting vs Downcasting in Java
Upcasting and downcasting in Java refer to the process of casting an object from one type to another. Upcasting is the process of casting an object to a higher or more generic type, while downcasting is the process of casting an object to a lower or more specific type. This is done by using the `instanceof` keyword.
Upcasting is a safe operation since the higher type can always accommodate the lower type, while downcasting is a risky operation since the lower type may not always be able to accommodate the higher type. Upcasting can be done implicitly, while downcasting must be done explicitly.
Upcasting is a process that moves an object up the inheritance hierarchy, while downcasting is a process that moves an object down the inheritance hierarchy. This means that upcasting may involve making an object more general, while downcasting involves making an object more specific.
In Java, upcasting allows an object to access methods and variables of the higher type, while downcasting allows an object to access methods and variables of the lower type. This is because upcasting is a widening process, while downcasting is a narrowing process.
Upcasting and downcasting can be used to take advantage of polymorphism. Polymorphism is a feature of object-oriented programming that allows an object to take on different forms depending on the context. Upcasting and downcasting enable an object to take on different forms and behave differently in different contexts.
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
.png)
Hosted By
Ryan Valles
Founder, Interview Kickstart

Our tried & tested strategy for cracking interviews

How FAANG hiring process works

The 4 areas you must prepare for

How you can accelerate your learnings
Register for Webinar
## Upcasting in Java
Upcasting in Java is the process of casting a subclass object to its superclass. This is also known as implicit casting, as no explicit typecasting is required. Upcasting is safe because a superclass type can contain all of the fields of its subclasses.
A sample code for upcasting in Java is shown below:
```java
// Create a subclass object
SubClass obj = new SubClass();
// Upcast the subclass object to its superclass
SuperClass obj2 = (SuperClass)obj;
```
## Downcasting in Java
Downcasting in Java is the process of casting a superclass object to its subclass. This is also known as explicit casting, as an explicit typecasting is required. Downcasting is not safe because a superclass type may not contain all of the fields of its subclasses.
A sample code for downcasting in Java is shown below:
```java
// Create a superclass object
SuperClass obj = new SuperClass();
// Downcast the superclass object to its subclass
SubClass obj2 = (SubClass)obj;
```