THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

3.4.3. Testing for Type


You can test the class of an object by using the instanceof operator, which evaluates to true if the
expression on its left is a reference type that is assignment compatible with the type name on its right, and
false otherwise. Because null is not an instance of any type instanceof for null always returns
false. Using instanceof you can safely downcast a reference, knowing that no exception will be
thrown. For example:


if (sref instanceof More)
mref = (More) sref;


Note that we still have to apply the castthat's to convince the compiler that we really meant to use the object as
a subclass instance.


Type testing with instanceof is particularly useful when a method doesn't require an object of a more
extended type but if passed such an object it can make use of the extended functionality. For example, a sort
method may accept a general List type as an argument, but if it actually receives a SortedList then it
doesn't have to do anything:


public static void sort(List list) {
if (list instanceof SortedList)
return;
// else sort the list ...
}


3.5. What protected Really Means


We noted briefly that making a class member protected means it can be accessed by classes that extend
that class, but that is loose language. More precisely, beyond being accessible within the class itself and to
code within the same package (see Chapter 18), a protected member can also be accessed from a class through
object references that are of at least the same type as the classthat is, references of the class's type or one its
subtypes. An example will make this easier to understand.


Consider a linked-list implementation of a queue, class SingleLinkQueue, with methods add and
remove for storing an object at the tail of the queue and removing the object from the head of the queue,
respectively. The nodes of the queue are made up of Cell objects that have a reference to the next cell in the
queue and a reference to the object stored in the current cell.


class Cell {
private Cell next;
private Object element;
public Cell(Object element) {
this.element = element;
}
public Cell(Object element, Cell next) {
this.element = element;
this.next = next;
}
public Object getElement() {
return element;
}
public void setElement(Object element) {

Free download pdf