Home Page Javascript Download Core Servlets & Java Server Java Cryptography Java in 60 Min A Day Javascript Tutorial About Us Contact Us
Site Search
Free Javascript Lessons
Newest Java Articles
Checkbox Changer
Check Entry
Check All
Block Key Press
Basic Validation
Auto Email Link
JavaScript Forms: Agree Before Entry
Auto Tab
JavaScript Calendars: Time Entered - Day Highlighted
JavaScript Calendars: Days Left
Related SE Keywords
Java virtual machine
Java Applet
Javascript Lesson
Javascript Tutorial
Java Programming
Java Games
Java Xml
Java String
Cryptography Extensions
Free Web Master Tools
JavascriptDownload.net > Free Javascript Lessons > Java in 60 Minutes a Day > 8- Polymorphism and Abstraction / The instanceof Keyword

The instanceof Keyword

In the CastDemo program in Listing 8.3, an Employee reference was cast to a

Salary reference. The cast was successful because the object being cast was

actually a Salary object. If we had attempted to cast the object to something

that it wasn’t, however, an exception would have occurred.

Let me demonstrate this with a specific example. The Salary class extends

Employee. Suppose that in Listing 8.4, the class named Hourly also extended


public class Hourly extends Employee


private double hourlyRate, hoursWorked;

public Hourly(String name, String address, int number,

double hourlyRate)


Listing 8.4 The Hourly class extends the Employee class. (continued)

Polymorphism and Abstraction 221

super(name, address, number);



public double getHourlyRate()


return hourlyRate;


public void setHourlyRate(double newRate)


if(newRate >= 0.0 && newRate <= 200.00)


hourlyRate = newRate;



public double getHoursWorked()


return hoursWorked;


public void setHoursWorked(double h)


if(h >= 0 && h <= 80)


hoursWorked = h;



public double computePay()


System.out.println(“Computing hourly pay for “ + getName());

if(hoursWorked <= 40)


return hourlyRate * hoursWorked;




return hourlyRate * 40.0

+ hourlyRate * 1.5 * (hoursWorked - 40);




Listing 8.4 (continued)

The following valid statements instantiate an Hourly object, referring to it

with an Employee reference. The reference is cast to Hourly to invoke the

methods of the Hourly class.

222 Chapter 8

Employee h = new Hourly(“Abe Lincoln”, “Springfield, IL”, 16, 8.00);

((Hourly) h).setHoursWorked(40);

((Hourly) h).computePay();


However, suppose I tried to cast the Hourly object to a Salary object:

Salary s = (Salary) h; //This compiles OK!

s.computePay(); //Which computePay() gets invoked?

Keep in mind that the compiler thinks h is an Employee, and casting an

Employee to a Salary is a compatible cast. This statement compiles, but there is

a problem looming. At run time, when h is cast to an Hourly object, a Class-

CastException will occur and the program will terminate. Java is very strict

about data types, and casting an Hourly object to type Salary is not valid

because the two types are not compatible.

By the way, invoking computePay() with s also compiles. Notice, too, in

the comment, that I asked “Which computePay() method gets invoked?”

More specifically, is it the computePay() in Hourly or the one in Salary?

The answer is neither because the cast one line above causes an

exception, and any ensuing statements will not execute.

What if you are not sure of the actual data type of h? Because h is of type

Employee, h can refer to an Employee object, a Salary object, or an Hourly

object. The instanceof keyword can be used to determine the data type of a reference.

The syntax for using instanceof looks like:

reference instanceof ClassName

The instanceof operator returns true if the reference is of the given class

type, and false otherwise. For example, before casting h to a Salary object, we

should have made the following check:

if(h instanceof Salary)


Salary s = (Salary) h;


//And so on


The cast above occurs only when h actually refers to a Salary object, so we

are guaranteed to avoid a ClassCastException when using the instanceof operator

in this manner.

Polymorphism and Abstraction 223

ClassCastException is the type of exception that occurs from poorly

written code. You should always use the instanceof operator to check the

data type of a reference before casting the reference, thereby averting any

chance of a ClassCastException.

The following InstanceOfDemo program in Listing 8.5 demonstrates the

instanceof operator. Study the program carefully and try to determine the output,

which is shown in Figure 8.2.

public class InstanceOfDemo


public static void main(String [] args)


Employee h = new Hourly(“Abe Lincoln”, “Springfield, IL”,

16, 8.00);

System.out.println(h.getName() + “ “ + h.getNumber());

if(h instanceof Salary)


System.out.println(“Casting to a Salary reference”);

Salary x = (Salary) h;

System.out.println(“Pay = “ + x.computePay());



else if(h instanceof Hourly)


System.out.println(“Casting to an Hourly reference”);

Hourly x = (Hourly) h;


System.out.println(“Pay = “ + x.computePay());



System.out.println(“\nDeliberately cast to the wrong type”);

Salary s = (Salary) h;



System.out.println(“End of main”);



Listing 8.5 The InstanceOfDemo program uses instanceof to verify the data type of a

reference before casting.

224 Chapter 8

Figure 8.2 The output of the InstanceOfDemo program.

Notice in the output of the InstanceOfDemo program in Figure 8.2 that the

statement “End of main” is not displayed. A ClassCastException occurs at

the statement:

Salary s = (Salary) h;

This exception causes main() to stop executing, and your program

terminates. Therefore, the last three statements in main() do not execute.

The flow of control when an exception occurs is discussed in detail in

Chapter 11, “Exception Handling.”

Add Comment
homepage   |  about us  |  contact us
Powered By teknonova.com