Link to home
Create AccountLog in
Avatar of Atkari
Atkari

asked on

query

Hello Expert,
           I have one query,plz tell me ,where it is use instanceOf  in java ,plz give me a sutable example,
           And explain in details.
                                   Thanks You.
Avatar of sunnycoder
sunnycoder
Flag of India image

if (objectA instanceofClassB)
will yield true if objectA can be upcast to objectB.

The instanceof operator will yield true if the right operand appears anywhere up the inheritance ladder of the left operand ... Typically (but not always ) you should not need it ... If your code is taking structure - if object iss of type A then do x else if object is of type b then do y, you must revisit your design.

Here is some saple code about usage of instanceOf
http://www.java2s.com/Code/Java/Language-Basics/Usetheinstanceofoperatorwithagenericclasshierarchy.htm
Avatar of Atkari
Atkari

ASKER

plz give me your own examples.
What is the point in me copy pasting same code here? ... Irrespective of who wrote the example, it should serve fine to help you gain an understanding of the topic ... If you have some doubs specific to the topic being discussed, feel free to ask.
Avatar of Atkari

ASKER

What is instanceOf  in java, plz help me , because i have no more knowledge about instanceOf

                                     Thank you

instanceOf tells you whether an object is an instance of a particular type of class. Since an object is a type of all classes that it has inherited from, instanceOf will yield true for all of them.

 if (objectA instanceofClassB)
Say you have a class hierarchy, and class B is derrived from class A.

Somewhere in the program, you might have the need to determine/check to see if an
object is a class A object, or a class B object.  This could occur because even though a
parameter in a method parameter was specified as class A, this does not mean that
a class B item can't be provided.

So, the method, you might, possibly, use the instanceOf() to determine whether or not
the object is of type B, instead of type A.

Does this help?
ASKER CERTIFIED SOLUTION
Avatar of reach2piyush
reach2piyush
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer