Through typecasting, we are not creating any new object in Java. But we are just providing another type of reference variable to the existing object. That is, we are performing typecasting and not object casting.
String str = new String(“Meet”);
Object obj = (Object)str;
This is essentially same as defining String object with an Object class reference in the following way:
Object str = new String();
Example of typecasting with an internal understanding
// main class public class Demo { public static void main(String[] args) { // Creating an Integer Object Integer i = new Integer(50); // Type casting integer object using reference of Number class Number num = (Number)i; // Type casting Number object using reference of Object class Object obj = (Object)num; // checking that all the reference variable are actually same System.out.println(i == num); System.out.println(obj == num); System.out.println(i == obj); } }
In this example, first, we are creating an Integer Object. Then, we type cast this Integer object using Number class reference variable.
Further, we typecast Number class variable using Object class variable. In the end, while comparing all the references, we get the following output.
Output:
true true true
Actually, there is only one object that gets created in this program. Other variables are just reference variables to that object.
Look at the following diagram.
As shown in the diagram, there is only one object and three different reference variables for the same object. Hence, the output shows true for all three comparisons.
Important Examples of Type Casting in Java
Parent reference can be used to hold child object. But by using that reference, we cannot call child specific methods. We can only call method available in the parent class.
In the below code, rules of method overriding are followed as per reference variable and runtime variable.
// class A class A { public void method() { System.out.println("Class A"); } } //class B class B extends A { public void method() { System.out.println("Class B"); } } //class C class C extends B { public void method() { System.out.println("Class C"); } } // main class public class Demo { public static void main(String[] args) { // Creating new object for class C. C c = new C(); // type casting C class object using B class reference variable B b =(B)c; // type casting B class variable using A class reference variable A a =(B)c; // calling method() on all 3 objects c.method(); b.method(); a.method(); } }
Output:
Class C Class C Class C
Since the latter two methods are the non-static methods, JVM executes method() of class C based on runtime object.
If we declare all the methods to be static then the output will be following based on reference type:
Class C Class B Class A
Similarly, type casting will follow variable resolution rules of overriding methods which are discussed in previous articles.
This is all about type casting in Java. Hope you find the tutorial helpful.