This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceof operator " Watch "instanceof operator " New topic

instanceof operator

premchand Singh
Ranch Hand

Joined: Mar 12, 2012
Posts: 43
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
Martin Vajsar

Joined: Aug 22, 2010
Posts: 3719

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

Joined: Mar 12, 2012
Posts: 43
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.
I agree. Here's the link:
subject: instanceof operator
It's not a secret anymore!