Way2Java

Object Casting Java

What is casting?

Assigning one data type to another or one object to another is known as casting. Java supports two types of casting – data type casting and object casting.

Conditions of assigning objects of different classes one to another
  1. Same class objects can be assigned one to another and it is what we have done with Officer1 class.
  2. Subclass object can be assigned to a super class object and this casting is done implicitly. This is known as upcasting (upwards in the hierarchy from subclass to super class).
  3. strong>Java does not permit to assign a super class object to a subclass object (implicitly) and still to do so, we need explicit casting. This is known as downcasting (super class to subclass). Downcasting requires explicit conversion.
Program explaining the above rules of Java Object Casting
class Flower
{
  public void smell()		// I
  {
    System.out.println("All flowers give smell, if you can smell");
  }
}   
public class Rose extends Flower
{
  public void smell()		// II
  {
    System.out.println("Rose gives rosy smell");
  }
  public static void main(String args[])
  {
    Flower f = new Flower();
    Rose r = new Rose();
				
    f.smell();	                // I
    r.smell();	                // II

    f = r;                      // subclass to super class, it is valid
    f.smell();		        // II

    // r  = f;	                // super class to subclass, not valid
    r = (Rose) f;               // explicit casting
    f.smell();			// II
  }
}



Output screen of Java Object Casting

The super class Flower includes only one method smell() and it is overridden by subclass Rose.

  
  f.smell();		// I
  r.smell();		// II

In the above two statements, nothing is new as both object are calling their own smell() methods. Observe the following two statements.

  f = r;                                           
  f.smell();

In the first statement, subclass object r is assigned (casted) to super class object f. It is a perfect assignment accepted by JVM and casting is done implicitly. In the super class object f, the subclass object reference (address) r exists. Calling f.smell(), f will call Rose smell() method.

From the above observation, a rule can be made as follows.

"If a subclass object is assigned to a super class object, the super class object will call subclass overridden method". This is an important rule which leads to dynamic polymorphism.

  //  r  = f;

The above statement does not compile as super class object is assigned to subclass object. To do it, we require explicit casting.

   r = (Rose) f;	// explicit casting
   f.smell();		// II

In the above statement, Flower object f is explicitly casted to Rose object r. In the earlier statement f = r, the f includes Rose reference. Now, f returns the Rose reference to Rose itself. For this reason f.smell() prints the subclass Rose smell(). That is, r is calling its own smell(). What happens if f = r does not exist earlier. It will be a an exception (not compilation error). That is, "before doing explicit casting, implicit casting must be done".

Object casting with Interface (getting interface objects)

With abstract classes and interfaces, objects cannot be created, but reference variables can be created. The above program is modified to suit interfaces. Here, Flower is an interface (and it can be abstract class also).

interface Flower
{
  public abstract void smell();
}
public class Rose implements Flower
{
  public void smell()
  {
    System.out.println("Rose gives rosy smell");
  }
   public static void main(String args[])
   {
     Flower f;
     Rose r = new Rose();
			
     r.smell();		                   // II

     f = r;                                // subclass object to super class reference variable
     f.smell();		                   // II

  // r  = f;                               // super class to subclass, not valid
     r = (Rose) f;	                   // explicit casting
     f.smell();		                   // II
   }
}

             
  Flower f;
  f = r;           // subclass object to super class reference variable
  f.smell();	   // II

The subclass object r is assigned to super class reference variable f. Here, f is a reference variable of interface Flower; but for this, the program is the same as earlier. When assigned, the reference variable works practically as an object. Like this, we can get the objects of interfaces and abstract classes, but we cannot create objects.

Learn more on Object casting problems.