1. Introduction
Casting in Java is a fundamental concept that allows one data type to be converted into another. It’s a crucial process to manipulate objects and variables in a program efficiently. In the real world, casting can be akin to converting a measurement from one unit to another, such as inches to centimeters.
In Java, casting is often used when working with polymorphism, when a superclass refers to an object of a subclass. We then need to access the subclass’s specific methods or properties and rely upon casting to achieve the same. This is essential since Java is a strongly typed language and variables are of specific data types.
In this tutorial, let’s take a deep dive into the nuances of these two options, evaluate their purposes, and subsequently highlight the best practices around each option.
2. Define Our Use Case
To illustrate the differences between the cast operator and Class.cast(), we’ll consider a fun use case involving a hierarchy of video game characters.
We’ll create an example with a superclass Character and subclasses Warrior and Commander. Our objective will be to learn how to cast a generic Character object to a specific subclass type to access its unique methods.
The use case involves creating instances of Warrior and Commander. These instances are stored in a list of Character objects. Later, they’re retrieved and cast back to their specific types. This casting allows calling subclass-specific methods.
3. Define Model Classes
*Let’s start by defining our first subclass, a Character namely Warrior with a method obeyCommand():*
public class Warrior extends Character {
public void obeyCommand(String command) {
logger.info("Warrior {} obeys a command {}", this.getName(), command);
}
}
Now, let’s create a second subclass of Character called Commander. This implements an issueCommand() method that issues a command to the warriors:
public class Commander extends Character {
public void issueCommand(String command) {
log.info("Commander {} issues a command {}: ", this.getName(), command);
}
}
4. The cast Operator
In Java, the cast operator is a straightforward option for converting one object type to another. We use parentheses to specify the target type.
To demonstrate this, let’s write a new class PlayGame that creates several characters (one of each type). Then it attempts to execute a command or issue a random command depending on whether the character is a Warrior or Commander.
Let’s begin by building some characters in a new class PlayGame:
public class PlayGame {
public List<Character> buildCharacters() {
List<Character> characters = new ArrayList<>();
characters.add(new Commander("Odin"));
characters.add(new Warrior("Thor"));
return characters;
}
}
We’ll now add the ability to play the game based on each character. Depending on our character, we either execute a given command or issue a new command. Let’s use the cast operator to demonstrate this:
public void playViaCastOperator(List<Character> characters, String command) {
for (Character character : characters) {
if (character instanceof Warrior) {
Warrior warrior = (Warrior) character;
warrior.obeyCommand(command);
}
else if (character instanceof Commander) {
Commander commander = (Commander)
character; commander.issueCommand(command);
}
}
}
In the above code, we used the approach called downcasting, which means we restrict the instance of the parent class to a derived class. This way the available operations are only limited to the derived class’s methods.
Let’s break down our implementation and understand the steps:
- In our PlayGame class, we define a method playViaCastOperator() which is given a list of characters and a command
- We iterate through the list of characters and perform specific actions depending on whether the character is a Warrior or a Commander. We use the instanceof keyword to confirm the types
- If the Character is a Warrior, we use the cast operator (Warrior) to get an instance of Warrior and invoke the obeyCommand() method
- If the Character is a Commander, we use the cast operator (Commander) to get an instance of Commander and invoke the issueCommand() method
5. The Class.cast() Method
Let’s see how to achieve the same using the Class.cast() method which is part of java.lang.Class.
We’ll now add a playViaClassCast() method to our PlayGame class to see this approach:
public void playViaClassCast(List<Character> characters, String command) {
for (Character character : characters) {
if (character instanceof Warrior) {
Warrior warrior = Warrior.class.cast(character);
warrior.obeyCommand(command);
} else if (character instanceof Commander) {
Commander commander = Commander.class.cast(character);
commander.issueCommand(command);
}
}
}
As we can see, we now use a Class.cast() to cast the Character to either a Warrior or a Commander.
6. Class.cast() vs cast Operator
Let’s now compare the two approaches against various criteria:
Criteria
Class.cast()
cast operator
Readability and Simplicity
Makes the type-casting explicit and clear, especially in complex or generic code where type safety is a concern
Used for simple casting operations where the type is known at compile time, favoring readability
Type Safety
Provides better type safety by making type checking explicit. This is especially useful in generic programming, where the type is unknown until runtime, ensuring type-safe casting and avoiding class cast issues
Doesn’t provide an explicit type check, which can lead to the dreaded ClassCastException if misused
Performance
Adds slight overhead due to the additional method call, but this is usually minor and outweighed by the benefits of type safety in complex scenarios
Provides a slight performance advantage as it’s a direct type cast, but the difference is negligible in most practical applications
Code Maintenance
Increases clarity in complex or generic codebases, making it easier to maintain and debug type issues
Easier to use and understand in simple scenarios, making code maintenance simpler for straightforward casts
Flexibility
Better suited for generic programming or frameworks that rely heavily on reflection, ensuring type safety and clarity
Not a great choice for generic programming
We should always validate the type before casting via the instanceof operator to avoid class cast exceptions. Utilizing libraries and frameworks can help handle casting and type-checking more robustly.
7. Conclusion
In this article, we’ve discussed the two casting options in Java and learned about their limitations and advantages using a relevant use case with a practical comparison.
Using the cast operator makes the casting process less verbose. It’s more concise compared to the Class.cast() method. However, both methods have their pros and cons. We need to consider these advantages and disadvantages carefully. The choice depends on our use case and the implementation context.
Considering the criteria listed in the above table, we can always make the right choice for casting.
As always, we can find the full code example over on GitHub.