Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof operator

 
premchand Singh
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic