• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Identifying subclass in an array

 
Larry Reynolds
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have created a multidimensional array of class Squares and am assigning some members of the array to a subclass (ie Hotel) of Squares. I need to be able to see what subclass, if any, has been assigned to the Square and then to perform operations on the square depending on which subclass it contains.

Here is some of the code:
Square[][] squares= new Square[10][4];
squares[1][2]=new Hotel();
if (square[1][2].getClass().getName()=="packagename.Hotel"){...

Is there a better way to do this? Especially, is there a way to ask for what object is in the array element without getting the package name back?

Thanks for your help.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The approach I would take is to list abstract methods in the superclass Squares that correspond to the methods that you are using in your subclasses. Then simply call the method on that entry in the array, and polymorphism will choose the correct implementation of the method based on the runtime type of the caller.
 
Scott Selikoff
author
Saloon Keeper
Posts: 4010
18
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using the java instanceof is superior object.getClass().getName() for comparison purposes for a number of reasons, but in particular because classes can have the same name but from different packages.

The other solution is also good but it requires you to make the method part of the parent class/interface (which it may not make sense to for all children classes), so the general solution would be to use instanceof.
 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way to do what you are talking about is to use the instanceof operator. Because of the equals comparison you are doing, your approach may or may not work depending on the compiler implementation. In general, you should compare Strings with String.equals(String).

However, Keith is right. You should be using polymorphism rather than hardcoded checks for the class. What if you make a new subclass of Squares? You would have to go in to your code and add another instanceof check. That's no good. Let OO do the work for you.
 
Larry Reynolds
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to everyone for your help. I will try to implement your suggestions and repost if needed. Best Wishes for the Holidays!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic