Pat Moloney
Pat Moloney

Reputation: 1

WHY would one want to use the instanceof operator?

I'm trying to answer this short answer question but I'm having a hard time understand what my instructor means by "why would we want to know this?". Any advice is greatly appreciated.

The question:

"What would be a use for the instanceof operator? Obviously it will designate if it is "an instance of" something--that is not the answer. The question is, why would we want to know that?"

Upvotes: 0

Views: 249

Answers (5)

Hui Zheng
Hui Zheng

Reputation: 10224

If one wants to downcast a type, he may need instanceof operator. But that usually indicates code smells.

You may refer to this article: "Prefer polymorphism over instanceof and downcasting".

UPDATE:

Seems the OP doesn't get the point of downcasting, let's explain in more detail.

Downcasting refines/narrows an object/value's apparent type to one of its subtype, such that it has the subtype's semantics.

This is useful when an object/value is declared as its supertype, but a caller needs some semantics or interfaces that are specifically in a subtype(i.e. those absent in the supertype). Only after the object/value passing the instanceof's test and being downcasted to that subtype, can the caller takes use of its specific semantics or interfaces.

Upvotes: 1

Govind Balaji
Govind Balaji

Reputation: 639

Take this situation, you have a superclass, reference which may refer to any of it derived class instance.
For example, There is a abstract class Clothes.Three classes Shirt, Shorts and Jeans are derived from it.

Clothes coolshirt=new Shirt();
Clothes coolshorts=new Shorts();
Clothes cooljeans=new Jeans();
Clothes gift=receiveGift();
if(gift instanceof Shirt)//Is the gift refers to a instance of Shirt
sendGratitude("Thanks for your new Shirt. It is really cool");
else if(gift instanceof Shorts)//Is the gift refers to a instance of Shorts
sendGratitude("Your shorts fits nice for me.Thank you.");
else if(gift instanceof Jeans)//Is the gift refers to a instance of Jeans
sendGratitude("In your Jeans I really look, Handsome, Very Thanks");

Upvotes: 0

Hot Licks
Hot Licks

Reputation: 47729

A very common place to need to use it is with JSON. You can receive a JSON value that is a "nest" of map-like and array-like items, and the type of, say, a particular element of an array-like item may be either map-like or array-like, depending on numerous factors.

So instanceof is used to sort this out, or at least make sure that the expected type is present, rather than attempting the cast and blowing up.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

The most obvious and very common (mis)use of the instanceof operator is deciding on special handling for a subclass:

void recordPayment(Payment pmt) {
    // Do something common for all subclasses
    recordAmount(pmt.getAmount());
    // Do something special for the credit card subclasses
    if (pmt instanceof CreditCardPayment) {
        CreditCardPayment ccPmt = (CreditCardPayment)pmt;
        recordCreditCardNumber(ccPmt.getCardNumber());
    }
}

The use of instanceof often indicates with near certainty that your design is missing a function in the base class and an override in the derived class.

Upvotes: 3

Depends on what you need. I use almost all time the "instance of", like when I'm working on variables with "Object" type, and etc.

A simple thing is using objects with different types in an array. For example:

Object[] data = new Object[4];

data[0] = "String";
data[1] = 32;
data[2] = 32.64D;
data[3] = new ArrayList<String>();

Then, you can check the contents:

if (data[0] instanceof String) {
  // Content at index '0' is a String
}

Upvotes: 0

Related Questions