I’m confused about how Java casting objects works.
For example, consider the following code:
Superclass variable = new Subclass();
(Superclass variable).method();
What exactly is happening here?
Does the type of the variable change, or is it the object inside the variable that changes?
I’m struggling to understand how casting affects objects in Java.
In Java, casting doesn’t change the object—it only affects how you reference it.
Your line:
Superclass variable = new Subclass();
is an example of upcasting. The object is still a Subclass, but you’re treating it as a Superclass.
Now, this line:
(Superclass variable).method();
does nothing because variable is already of type Superclass. You don’t need to cast explicitly here.
If you want to access subclass-specific methods, you need downcasting:
((Subclass) variable).subclassMethod();
This tells Java:
“Hey, I know this object is really a Subclass, so let me use its methods!”
Be careful! If variable wasn’t actually a Subclass, you’d get a ClassCastException. Always check using instanceof before downcasting:
if (variable instanceof Subclass) {
((Subclass) variable).subclassMethod();
}
Great explanation! But why does Java even need casting?
Java is statically typed, meaning the compiler enforces type safety. Without casting, the compiler wouldn’t let you call subclass-specific methods on a superclass variable.
For example, let’s say you have a list of Superclass objects, but you know some are actually Subclass:
List<Superclass> list = new ArrayList<>();
list.add(new Subclass());
for (Superclass obj : list) {
if (obj instanceof Subclass) {
((Subclass) obj).subclassMethod();
}
}
Here, instanceof ensures safe downcasting so you can access Subclass methods.
So, casting doesn’t change the actual object—it just tells the compiler how to treat it.
Yep, but casting isn’t always ideal. What if you downcast incorrectly?
Superclass obj = new Superclass();
Subclass sub = (Subclass) obj; // ClassCastException
This will crash at runtime because obj is not actually a Subclass.
Better Approaches Instead of Casting:
-
If you override methods in the subclass, you don’t even need downcasting:
Superclass variable = new Subclass();
variable.someMethod(); // Calls Subclass version if overridden!
-
Instead of downcasting, design your classes to use abstract methods or interfaces so you don’t have to check types manually.