• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to check if an object of a class is equal to a particular class (including parent/children)?  RSS feed

 
Hans Hovan
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure if I worded that correctly. Hopefully this makes sense:

Say I have super class 'fruit' and a bunch of child classes 'apple', 'orange', etc. If I were to do something like:

.

How could I check to see if the returned type is a 'fruit' or child of fruit?

So, if I had something like:



Is the code able to tell that apple is a subclass of fruit?

Or is there a better way to do this? Thanks.




 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Presuming that "Apple" is the name of the class, then perhaps what you are asking for is this:



Another possibility is this:



you should note that those two are different tests; the first tests whether the object is an instance of the Apple class, and the second tests whether the object can be assigned to a variable of type Apple. So if you had a Spartan class which was a subclass of Apple, and typeOfFruit referred to a Spartan object, then the first would be false and the second would be true.


 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hans Hovan wrote:Is the code able to tell that apple is a subclass of fruit?

Just to add to Paul's good advice: you need to be absolutely clear about what you mean by "subclass".

If you want to be sure that the object really is a subclass (ie, it's an Apple or an Orange, but NOT simply a Fruit), then there are two possibilities:

1. You can combine Paul's suggestions, ie:
if (typeOfFruit instanceof Fruit && typeOfFruit.getClass() != Fruit.class) { ...

2. Fruit is an interface or an abstract class, in which case 'instanceof Fruit' is all you need because typeOfFruit can't possibly just be a Fruit.

Indeed, instanceof is almost always sufficient for these sorts of tests.

HIH

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!