Weird behaviour of if(x instanceof X)

I have a class PartA and a class PartB which is a derived class of PartA. I have a list of type PartA which holds both parts a and b. And I need to determine which kind of class it actually is when I loop through it. But if I do this:

for (PartA i : parts) {
    if (i instanceof PartA) {
        //some logic
    }

It will still give true regardless of which class it actually is: a or b.

Am I doing something wrong or if not, what can I do to acheive desired result?

Answers


This behavior is by design. Instance of B are also instances of A.

You want

if (i.getClass() == A.class)

Instances of PartB are also instances of PartA. Always check for the most derived type first. (Read instanceof X as "is an instance of X or a derived type of X.")

Or, better yet, use polymorphism to your advantage -- can this logic be moved into a method of PartA that you could override on PartB? Then you would not have to actually test the type of the object, you would just let virtual method dispatch figure that out for you.


Need Your Help

Javadoc multiple packages

java documentation package javadoc

I am trying to generate java documentation for multiple packages so I have a single index.html, I can generate them fine for single packages by writing,

FB ID is returning as undefined

javascript jquery facebook facebook-graph-api access-control

I am using var userID = (FB.getAuthResponse() || {}).userID; to get ID of logged in user, FB .init is initialized properly.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.