What are upcasting and downcasting in Java, and which one does the compiler do for you?
Upcasting is when you go from a more specific type to a more general one. Downcasting is when you go back the other way.
Upcasting is always safe, because every dog really is an animal. So the compiler does it for you without asking, and it can never fail while the program runs.
public class Main {
public static void main(String[] args) {
// Upcasting: widening reference conversion, always safe, implicit.
Animal animal = new Dog();
// The same thing written out.
Animal other = (Animal) new Cat();
System.out.println("animal : " + animal.describe());
System.out.println("other : " + other.describe());
// Downcasting: narrowing, explicit, and checked while it runs.
Dog dog = (Dog) animal;
System.out.println("dog : " + dog.fetch());
}
}
class Animal {
String describe() {
return "an animal";
}
}
class Dog extends Animal {
@Override
String describe() {
return "a dog";
}
String fetch() {
return "fetched the ball";
}
}
class Cat extends Animal {
@Override
String describe() {
return "a cat";
}
}
Downcasting is the opposite. It is always explicit, because the compiler cannot know whether the object really is the more specific type. It is also checked while the program runs, so a wrong cast throws an error at that moment rather than at compile time.
So the answer to the question is this. The compiler does upcasting for you whenever it can, and it never fails. You have to write a downcast yourself, and it can fail while the program is running.
The next question in this topic looks at what that failure looks like.