1

Java: how to tell if an object is of a specific subclass.

I want to have a check to see if an object is of a particular subclass and have the check NOT come back true for other classes that have inherited from the same superclass.

So, for example:

superclass: fruit

subclass: apple and banana extend fruit

Then I have a check (if appleObject.isThisClass(apple)) {do stuff}

So far all I've been able to find are ways to check that will still return true because they share the same superclass.

Hopefully that makes sense.

Thanks for the help.

1
  • 3
    Please look over this tutorial on polymorphism. Performing a check like this is almost certainly the wrong approach. Commented Apr 12, 2014 at 2:10

2 Answers 2

3

Assuming you have an object reference apple of type Banana or Apple; then something like this,

if (apple instanceof Apple) // true 

tells you if apple is of type Apple. Where as

if (apple instanceof Banana) // false 

Would exclude Banana and finally

if (apple instanceof Fruit) // true 

would include Banana or Apple; but you should probably not be testing this in callers (tight coupling) - instead, you should try and encapsulate behavior in the Fruit "interface".

EDIT

Given your additional question in the comment,

Fruit aFruit = aMethod(); // get a fruit. if (aFruit instanceof Apple) { Apple apple = (Apple) aFruit; // do apple things with the apple. apple.somethingOnlyApplesDo(); } // else if (aFruit instanceof Banana) { // Do Nothing With Bananas. // Banana banana = (Banana) aFruit; // } 
Sign up to request clarification or add additional context in comments.

6 Comments

if the 'appleObject' is actually a subclass of 'Apple' the appleObject instanceof Apple will also return true.
Is there a way to test this though: if (apple instanceof Apple) // true if (apple instanceof Fruit) // FALSE ?
@user3448228 Not using instanceof. Because every apple is also a fruit! You can call getClass(), but again - this is not a good idea, because it is very "tight coupling".
@user3448228 What are you actually trying to achieve with this?
I have a method that returns a fruit (it could be either an apple or a banana depending). So, basically: fruit aFruit = aMethod(); Then I have an if statement that does a check on aFruit and if it is an apple stuff happens and if it is a banana nothing happens. Hopefully that makes sense. Its possible I just set all of this up in a bad way (still learning).
|
2

Use the getClass() method that is inherited from Object.

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#getClass%28%29

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.