Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   4. Object-Oriented Concepts  >   4.13. Object type casting

4.13. Object type casting
Last updated: 23 January 2013.

This tutorial explains how to cast an object to a different type.

Let's return to the class Aircraft that I have used in the previous tutorials:

public class Aircraft {

   
// The class body goes here

}

The class Plane shown below is a subclass of the class Aircraft:

public final class Plane extends Aircraft {

   
// The class body goes here

}

A plane is an aircraft but an aircraft is not a plane. Consequently, if you write the following statements, you will get a compilation error at the second statement:

Aircraft aircraft = new Plane();
Plane plane = aircraft;

The reason for the compilation error is that although the variable aircraft is instantiated as a Plane object at runtime, its type is Aircraft at compile time. Consequently, the variable aircraft cannot be assigned to a variable of type Plane.

However, you can get around that problem by casting the variable aircraft to the type Plane as shown below:

Aircraft aircraft = new Plane();
Plane plane =
(Plane) aircraft;

At runtime, when executing the second statement, the type of the variable aircraft will be checked. If that type is not Plane, a ClassCastException will be thrown.

The keyword instanceof allows you to check the type of an object at runtime. For example, before casting the variable aircraft to the type Plane, you can check its type as follows:

Aircraft aircraft = new Plane();
Plane plane;

if(aircraft instanceof Plane)
   
plane = (Plane) aircraft;

Note that instead of using the class Aircraft as the super class of the class Plane, you can use the class Object which is the super class of all classes:

Object object = new Plane();
Plane plane;

if(object instanceof Plane)
   
plane = (Plane) object;


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   4. Object-Oriented Concepts  >   4.13. Object type casting
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   4. Object-Oriented Concepts  >   4.14. Garbage collection

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7