aspose file tools*
The moose likes Beginning Java and the fly likes Could someone explain the purpose of instance? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Could someone explain the purpose of instance?" Watch "Could someone explain the purpose of instance?" New topic
Author

Could someone explain the purpose of instance?

kenny gill
Ranch Hand

Joined: Mar 12, 2012
Posts: 54

I'm trying to answer this question but am a little confused on how to answer it:

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?
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2615
    
    9

I will use the instanceof operator to check if a variable is of some class.



K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5 OCPBCD5
kenny gill
Ranch Hand

Joined: Mar 12, 2012
Posts: 54

So, the purpose of it is to check if a variable is of some class?
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2615
    
    9

kenny gill wrote:
So, the purpose of it is to check if a variable is of some class?


That's one purpose. There may be others. What do the others think?
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Like Tsang said, it is used to check if an object belongs to a particular class or not. Why would you want to check that? Well, as you learn more and more about the Java language and how it is used in practical situations, only then would you be able to fully grasp its significance. One is the case when you override public boolean equals() method of Object class to implement your own notion of when 2 objects(which are of type T and not a primitive) must be treated as equal. Only when you are sure about the object "o" being an instance of a particular class type "T" can you use it to invoke methods of that class.

Let me explain with a simple example that I can now think of:

Let's say you have a collection , say an ArrayList of objects. It can hold any type of object(Integer,String,Float or even your defined class type T).

Say like this

Now I ask you to find the length of the all the String elements in the list. How will you do that?


~ Mansukh
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8414
    
  23

kenny gill wrote:So, the purpose of it is to check if a variable is of some class?

Actually, its a type checker, because it will return true if the supplied object (the left-hand operand) is the same class as the type on the right, or a subclass of it.

For a strict class check, you need:
obj.getClass().equals(classToCheckFor.class)

Personally, I prefer instanceof for these reasons:
  • 1. It's quicker than getClass().
  • 2. It's more generic.
  • 3. It eliminates the cases where obj == null (it returns false) without throwing a NullPointerException.
  • 4. You can use it with interface types.
  • although there are rare cases - eg, when writing equals() methods - where you really need getClass().

    But don't get into the habit of writing equals() methods with getClass() just because of that. It's the exception rather than the norm that it makes any difference which one you choose, and using getClass() can break LSP, which you'll learn about later.

    Winston

    Isn't it funny how there's always time and money enough to do it WRONG?
    Articles by Winston can be found here
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40034
        
      28
    If you find yourself using instanceof, you may be straying for the principles of object‑orientation. You should design your app so you don’t need to know the runtime type of objects.
    Mansukhdeep Thind
    Ranch Hand

    Joined: Jul 27, 2010
    Posts: 1157

    Campbell Ritchie wrote:If you find yourself using instanceof, you may be straying for the principles of object‑orientation. You should design your app so you don’t need to know the runtime type of objects.


    Hmm.. Wise words Ritchie..
    Winston Gutkowski
    Bartender

    Joined: Mar 17, 2011
    Posts: 8414
        
      23

    Campbell Ritchie wrote:If you find yourself using instanceof, you may be straying for the principles of object‑orientation.

    I totally agree with that statement in general; however, there are a couple of situations where you may not have a choice:
    1. When writing an equals() method (when is Java going to offer a typed version of that darn thing? ).
    2. When checking to see if an object implements a marker interface - the most obvious one being RandomAccess - since it might make a big difference as to how you proceed.

    @kenny: However, what Campbell said is absolutely correct; you should avoid type-checking as much as you possibly can.

    Winston
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40034
        
      28
    Winston Gutkowski wrote: . . . 1. When writing an equals() method (when is Java going to offer a typed version of that darn thing? ). . . .
    Never. The idea of equals() is that it takes Object as its parameter and then does the type‑checking afterwareds.

    And I said “may”, which implicitly permits exceptions. So I think we agree about that.
    Winston Gutkowski
    Bartender

    Joined: Mar 17, 2011
    Posts: 8414
        
      23

    Campbell Ritchie wrote:Never. The idea of equals() is that it takes Object as its parameter and then does the type‑checking afterwareds.

    You're probably right, but since 90% or more of the time, we're only interested in comparing like objects, a
    public boolean equals(T other) { ...
    method would be darn useful, and would eliminate an awful lot of repeated boilerplate.

    Too late now, I suspect.

    Winston
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40034
        
      28
    The problem is that lots of code including the entire collections framework is written on the assumption that equals() takes Object as its parameter type. If you are looking for equality and the method has been overloaded rather than overridden, you will get false negatives (i.e. false when you expected true).
    Winston Gutkowski
    Bartender

    Joined: Mar 17, 2011
    Posts: 8414
        
      23

    Campbell Ritchie wrote:The problem is that lots of code including the entire collections framework is written on the assumption that equals() takes Object as its parameter type. If you are looking for equality and the method has been overloaded rather than overridden, you will get false negatives (i.e. false when you expected true).

    No, I quite understand the issues. I still think it might be possible to add an Equatable<T> (ugh, horrible name I know; but hopefully you get the idea) interface that a Java Object recognises (in the same way that it does Cloneable) and has its equals() method run the interface method (equalTo()?) rather than its own if it sees it. You could even include hashCode() with it.

    Like I say, probably tilting at windmills.

    Winston
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40034
        
      28
    Still better than an Equable interface

    Edit Change word in to a link.
    Paul Clapham
    Bartender

    Joined: Oct 14, 2005
    Posts: 18987
        
        8

    And would the equivalent of a Comparator be an "Equator" in that case?
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40034
        
      28
    I’d be Line if I said No.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Could someone explain the purpose of instance?