Object Casting in Java Inheritance: Upcasting and Downcasting
When you have a subclass, you can always assign an instance of that subclass to a reference variable of its superclass without any explicit casting. This is called “upcasting”. Upcasting is safe because the subclass has all the methods and fields of the superclass (plus possibly more).
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
// Upcasting
Animal animal = new Dog();
animal.eat(); // Valid because eat() is a method in Animal
// animal.bark(); // Invalid because bark() is not a method in Animal
In this example, Dog
is a subclass of Animal
. An instance of Dog
can be upcast to Animal
without any explicit cast.
Downcasting (Explicit)
Downcasting is the casting of a superclass reference to a subclass reference. Downcasting requires an explicit cast because it can potentially lead to a ClassCastException
at runtime if the object being downcast is not actually an instance of the subclass.
// Downcasting
Animal animal = new Dog(); // Upcasting
Dog dog = (Dog) animal; // Downcasting
dog.bark(); // Now valid because dog is a reference of type Dog
In this case, animal
is actually an instance of Dog
, so the downcast is valid.
Invalid Downcasting (Causing ClassCastException
)
A ClassCastException
occurs when you try to downcast to a subclass but the object is not an instance of that subclass.
Animal animal = new Animal(); // Just an Animal, not a Dog
Dog dog = (Dog) animal; // This will throw a ClassCastException at runtime
Here, animal
is not an instance of Dog
; it's just an Animal
. The downcast is invalid and will throw an exception.
Casting Between Siblings (Invalid)
If two classes share the same parent, they are “siblings” in the class hierarchy. You cannot cast siblings to each other because they potentially have different methods and fields.
class Cat extends Animal {
public void meow() {
System.out.println("The cat meows.");
}
}
Dog dog = new Dog();
Cat cat = (Cat) dog; // INVALID: A Dog is not a Cat
Even though both Dog
and Cat
are subclasses of Animal
, you cannot cast a Dog
to a Cat
or vice versa.
Upcasting to a superclass is always allowed and can be implicit.
Downcasting to a subclass must be explicit and is only valid if the object is truly an instance of that subclass.
Casting between subclass “siblings” is invalid and will result in a
ClassCastException
.