The instanceof Operator And Casting Objects

The instanceof Operator

Given that you can pass objects around using references to their parent classes, sometimes you might want to know what actual objects you have. This is the purpose of the instanceof operator. Suppose the class hierarchy is extended so that you have the following:

public class Employee extends Object

public class Manager extends Employee

public class Engineer extends Employee

Note –
Remember that, while acceptable, extends Object is redundant. It is shown here only as a reminder. If you receive an object using a reference of type Employee, it might turn out to be a Manager or an Engineer. You can test it by using instanceof as follows:

public void doSomething(Employee e) {

if ( e instanceof Manager ) {

// Process a Manager

} else if ( e instanceof Engineer ) {

// Process a Engineer

} else {

// Process any other type of Employee



Note – In C++, you can do something similar using runtime-type information (RTTI).

Casting Objects

In circumstances where you have received a reference to a parent class, and you have determined that the object is, in fact, a particular subclass by using the instanceof operator, you can access the full functionality of the object by casting the reference.

public void doSomething(Employee e) {

if ( e instanceof Manager ) {

Manager m = (Manager) e;

System.out.println(“This is the manager of ”

+ m.getDepartment());


// rest of operation


If you do not make the cast, an attempt to execute e.getDepartment() would fail because the compiler cannot locate a method called getDepartment in the Employee class. If you do not make the test using instanceof, you run the risk of the cast failing. Generally, any attempt to cast an object reference is subjected to several checks:

● Casts upward in the class hierarchy are always permitted and, in fact, do not require the cast operator. They can be done by simple assignment.

● For downward casts, the compiler must be satisfied that the cast is at least possible. For example, any attempt to cast a Manager reference to a Engineer reference is not permitted, because the Engineer is not a Manager. The class to which the cast is taking place must be some subclass of the current reference type.

● If the compiler permits the cast, then the object type is checked at runtime. For example, if it turns out that the instanceof check is omitted from the source, and the object being cast is not in fact an object of the type it is being cast to, then a runtime error (exception) occurs. Exceptions are a form of runtime error and are the subject of a later module.