[java] [SOLVED]Can i determin if a class has a particular method?

Started by
12 comments, last by relequestual 15 years, 1 month ago
Yes, if you do things that way, then Building's canRotate() method will override Item's.
public class Item {  public boolean canRotate() {    return false;  }}public class Building extends Item {  public boolean canRotate() {    return true;  }}(test code)ArrayList<Item> items = new ArrayList<Item>();items.add(new Item());items.add(new Building());for(Item item : items) {  if(item.canRotate()) System.out.println("This item can rotate.");  else System.out.println("This item cannot rotate.");}

In this situation (and it may not fit what you are trying to model), Building *is* everything that an Item is, and more. AbleToBePlacedOnAGrid was just an example class, you don't really need it. If you wanted to inherit from a general superclass for your game model, then you should call it something like GameObject or Entity or GridObject (Building extends GridObject, Item extends GridObject).
Advertisement
Thanks Argus2 for your very clear reply. You have been of grate help!

That does indeed look like what I need. At current, I have no objects which are non usable.

Question about your test code, I see you set the arraylist type to Item.
Does that allow any class that it inherits to also be part of the arraylist? Sorry thats probably really simple, but we have only recently been introduced to arraylists.

Thanks again Argus2

If you ever require any sort of freeware, I can probably find it for you. I'm know lots of freeware :)
Does that allow any class that it inherits to also be part of the arraylist?

Any class that inherits Item, not the other way around.
thanks Haladria :)
That is indeed what I meant to say. Guess I said it wrong.
Awesome! That solves a few problems. cheers!

Thanks again for all help in this thread.

Will be sure to come back here for help again!

Note:
Just to anyone reading this thread, Argus2's last post, the Item class would return false as default, where as the usableItem class would return true, and not the Building class, as the buildings cannot be rotated.

I changed the Item class to GridObject as suggested.
Then I have an Item class which has rotation, and a UsableItem class which has a point of use.

[Edited by - relequestual on February 21, 2009 7:09:19 AM]

This topic is closed to new replies.

Advertisement