CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Inheritance

Inheritance
More skills
Cast objects

Suppose you want to assign the object reference o to a variable of the Student type using the following statement:

Student b = o;
A compilation error would occur. Why does the statement Object o = new Student() work and the statement Student b = o doesn't? This is because a Student object is always an instance of Object, but an Object is not necessarily an instance of Student. Even though you can see that o is really a Student object, the compiler is not so clever to know it. To tell the compiler that o is a Student object, use an explicit casting. The syntax is similar to the one used for casting among primitive data types. Enclose the target object type in parentheses and place it before the object to be cast, as follows:
Student b = (Student)o; // Explicit casting

How to cast objects

  • Java can implicitly cast a subclass to a superclass. So you can use a subclass whenever a reference to its superclass is called for.
  • Example: You can specify a Book object whenever a Product object is expected because Book is a subclass of Product.

  • You must explicitly cast a superclass object when a reference to one of its subclasses is required.
  • Example: You must explicitly cast a Product object to Book if a Book object is expected. If the Product object isn't a valid Book object, a ClassCastException will be thrown.

  • Casting affects the methods that are available from an object.
  • Example: If you store a Book object in a Product variable, you can't call the setAuthor method because it's defined by the Book class, not the Product class.

Casting examples that use the Product and Book classes

Book b = new Book();
b.setCode("java");
b.setDescription("Murach's Beginning Java 2");
b.setAuthor("Andrea Steelman");
b.setPrice(49.50);

Product p = b;            // cast Book object to a Product object
p.setDescription("Test"); // OK - method in Product class
//p.setAuthor("Test");    // not OK - method not in Product class

b = (Book) p;       // cast the Product object back to a Book object
b.setAuthor("Test");    // OK - method in Book class

Product p2 = new Product();
Book b2 = (Book) p2;    // will throw a ClassCastException because
                        // p2 is a Product object not a Book object
Previous | Object's type | Cast objects | Compare objects | Next