Reference casting in Java allows you to treat an object reference as another type. This feature is primarily used in the context of class hierarchies (inheritance).
Types
- Upcasting
- Downcasting
Upcasting
Upcasting is a process in Java where a subclass reference is cast to a superclass reference. Upcasting allows to treat an instance of a subclass as if it were an instance of its superclass.
Upcasting is automatically handled by the Java compiler, so no explicit cast is necessary.
When upcasting, only the members (methods and fields) declared in the superclass are accessible, not the subclass-specific members.
Upcasting is always safe and does not throw any exceptions.
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = dog; // Upcasting
animal.eat(); // This animal eats food
// animal.bark(); // Error: cannot find symbol
}
}
Downcasting
Downcasting in Java is the process of converting a reference of a superclass type to a reference of a subclass type. This operation can be risky and requires explicit casting because it assumes that the object being cast is actually an instance of the subclass. If an object is not actually of the type to which it is being cast, a ClassCastException
will be thrown at runtime.
Downcasting must be explicitly stated in the code. Downcasting allows access to members (methods and fields) specific to the subclass that are not accessible through the superclass reference.
Use instanceof
to ensure the actual type before downcasting.
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
animal.eat(); // This animal eats food
if (animal instanceof Dog) { // Type check
Dog dog = (Dog) animal; // Downcasting
dog.bark(); // The dog barks
}
}
}