Can we cast reference variables in Java?


Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects).

Casting in Java

Converting one primitive data type into another is known as type casting.

Example

import java.util.Scanner;
public class TypeCastingExample {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer value: ");
      int i = sc.nextInt();
      long num = i;
      System.out.println("Value of the given integer: "+num);
   }
}

Output

Enter an integer value:
421

Casting in referenced datatypes

Yes, you can cast the reference(object) of one (class) type to other. But, one of the two classes should inherit the other.

For example, Assume we have a class with name Person with two instance variables name and age and one instance method displayPerson() which displays the name and age.

public class Person{
   private String name;
   private int age;
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void displayPerson() {
      System.out.println("Data of the Person class: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
   }
}

Another class named Student extends the person class and in addition to the inherited name and age it has two more variables branch and student_id. It has a method displayData() which displays all four values.

public class Student extends Person {
   public String branch;
   public int Student_id;
   public Student(String name, int age, String branch, int Student_id){
      super(name, age);
      this.branch = branch;
      this.Student_id = Student_id;
   }
   public void displayStudent() {
      System.out.println("Data of the Student class: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Branch: "+this.branch);
      System.out.println("Student ID: "+this.Student_id);
   }
   public static void main(String[] args) {
      ..............
   }
}

Converting sub class variable to super class type

Now, in the main method you can create objects of the both classes separately and convert super class object to sub class directly.

public static void main(String[] args) {
   //Creating an object of the Student class
   Student student = new Student("Krishna", 20, "IT", 1256);
   //Converting the object of Student to Person
   Person person = new Person("Krishna", 20);
   //Converting the object of student to person
   person = (Student) student;
   person.displayPerson();
}

Output

Data of the Person class:
Name: Krishna
Age: 20

In short, super class reference variable can hold the sub class object. But, using this reference you can access the members of super class only, if you try to access the sub class members a compile time error will be generated.

Example

public static void main(String[] args) {
   Person person = new Student("Krishna", 20, "IT", 1256);
   person.displayStudent();
}

Output

Student.java:33: error: cannot find symbol
      person.dispalyStudent();
             ^
   symbol: method dispalyStudent()
  location: variable person of type Person
1 error

Converting super class variable to sub class

In the same way you can try to convert the super class variable to the sub class to do so unlike the previous scenario you need to use the cast operator.

Example

public static void main(String[] args) {
   //Creating an object of the Student class
   Student student = new Student("Krishna", 20, "IT", 1256);
   //Converting the object of Student to Person
   Person person = new Person("Krishna", 20);
   //Converting the object of person to student
   student = (Student) person;
   student.displayPerson();
   student.displayStudent();
}

To this reference, members of both classes are available and the program gets compiled successfully.

But, when you try to execute it, an exception will be raised as shown below −

Exception in thread "main" java.lang.ClassCastException: ther.Person cannot be cast to ther.Student
at ther.Student.main(Student.java:41)

To resolve this issue, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator.

Example

public static void main(String[] args) {
   //Converting the object of Student to Person
   Person person = new Student("Krishna", 20, "IT", 1256);
   //Converting the object of person to student
   Student student = (Student) person;
   student.displayPerson();
  student.displayStudent();
}

Output

Data of the Person class:
Name: Krishna
Age: 20
Data of the Student class:
Name: Krishna
Age: 20
Branch: IT
Student ID: 1256

Updated on: 06-Aug-2019

937 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements