2.9 Object Assignments2.8 Type Compatibility2 Java with Caffeine2.10 Static Types and Dynamic Types

2.9 Object Assignments

Above rule has a technical consequence in Java. A variable/constant whose type is a superclass may refer to an object of the subclass. For instance, since an object of type Book is also of type Article, we may write:

   Article a = new Book(...);

However, since also an object of type CD is of type Article, we may change the assignment:

   a = new CD(...);

We therefore don't see a priori whether a variable of type Article holds a book or a CD. However, this does not matter, because we can refer via this variable only to the fields and methods declared in class Article (which are inherited by both Book and CD).

   String t = a.getTitle();
   int p = a.getPrice();

If we want to know whether a variable of type Article holds a book, we can check this with the predicate instanceof and convert the type of the object by a type cast to Book.

   if (a instanceof Book)
   {
     Book b = (Book)a;
     ...
   }

The instanceof check ensures that the type cast to Book is correct. If the check is omitted and the Article variable holds an object of type CD, the type cast triggers a runtime error.

Generalizing our discussion, let us assume that we have a subclass D of C:

   class D extends C
   {
     ...
   }

Then we can always assign to a variable of type C an object of type D (because a D object is also a C object):

   D d = ...
   C c = d;

However, we can assign to a variable of type D only a variable of type C with a type cast and after we have checked that the C variable actually holds a D object:

   C c = ...;
   if (c instanceof D)
   {
     D d = (D)c;
     ...
   }


© Wolfgang Schreiner; February 3, 2005

2.9 Object Assignments2.8 Type Compatibility2 Java with Caffeine2.10 Static Types and Dynamic Types