wood burning stoves 2.0*
The moose likes Java in General and the fly likes instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceof operator " Watch "instanceof operator " New topic
Author

instanceof operator

premchand Singh
Greenhorn

Joined: Mar 12, 2012
Posts: 28
Hi i have doubt in instanceof operator, below is the code i have written

Class someclass(){
new A();
new B();
new C();
new D();

A ob=new A();
ob = new C();

System.out.println("ob now refers to c");
if (ob instanceof A)
System.out.println("ob can be cast to A");
if (ob instanceof C)
System.out.println(" ob can be cast to C");
}
}

i am not getting once i have assigned the ob operator to C then also 1st statement is also being printed.how???
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3610
    
  60

You didn't specify the hierarchy of your classes, so it's hard to tell. However, keep in mind that an object which is an instance of a certain class is also an instance of all parents of that class (direct or indirect). Furthermore, if a class implements some interfaces, instances of that class are also instances of all implemented interfaces. The instanceof operator follows these rules.

It might help if you name your classes using some real-world objects. For example, you could have a class Animal, with subclasses Cat, Dog and Cow. It is quite apparent that a dog is also an animal (so dog instanceof Animal will evaluate to true), but not all animals are dogs (and therefore animal instanceof Dog can generally evaluate either to true or false). Just to clarify, variable dog would be declared as Dog and animal as Animal in the this example.

If you have more questions, feel free to ask again, but it would be useful if you post the code you really used (your example does not compile), and enclose the code in code tags. See PostRealCode and UseCodeTags (click these links) for details.
premchand Singh
Greenhorn

Joined: Mar 12, 2012
Posts: 28
Thanks Martin Vajsar i got the clarification sorry for not giving the class hierarchy actually the hierarchy was like that..
lass A {
int i, j;
}

class B {
int i, j;
}
class C extends A {
int k;
}
class D extends A {
int k;
}

After your answer i got the clarification.
Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof operator