How to Convert Java Objects
The Java programming language was unique when it was first released in the mid 1990s in that the language was designed to be a hierarchy of classes. Unlike C++, which extended the C programming language and added the concept of programming classes, everything in Java is related to the object-oriented programming structure. A common task that arises for a programmer is converting an instance of a class, or class object, to another class type. This can be done in Java through class casting.
Instructions
-
-
1
Open the Java class file that you need to convert, or cast Java objects in your integrated development environment (IDE) or text editor.
-
2
Confirm that the Java object you intend to cast or convert to another class is related by inheritance by viewing the Java documentation of the two classes. When viewing the inheritance hierarchy of each class, they should share a common class in this hierarchy in order for you to convert the two objects.
-
-
3
Enter the class name that you are going to convert the desired object to in parentheses beside the name of the object that is being converted. The "classnameyouareconvertingto" is the name of the destination class in the casting. An example of the code required to cast a Java object to an instance of another class is
"(classnameyouareconvertingto)objectbeingconverted". -
4
Save, compile and run your updated Java class. If you see errors when you compile the class, it will be due to attempting to convert between classes that are not related by inheritance. The same rules will also apply if you are going to cast objects to Interface classes.
-
1