EDIT: This is not a duplicate because I am addressing on issue where the classes cannot be overloaded to achieve polymorphism. I am not asking for comparison between polymorphism vs instanceof. I am asking a very specific scenario-based question.
I have read it n
times online that one should always try to avoid the usage of instanceof
operator, unless we are using it to implement the .equals()
method of a class.
It was said that, whenever possible, we should try to achieve polymorphism rather than using instanceof
to determine the type of the objects to decide the following actions.
For example: http://www.javapractices.com/topic/TopicAction.do?Id=31
However, in this specific scenario where I do not have any available methods in the super & sub classes (other than the toString, equals, accessor & mutator methods). Is it a valid scenario to use instanceof
?
class Warrior
{
int damage;
int defense;
Item handSlot;
public Warrior(){
damage = 0;
defense = 0;
handSlot = null;
}
private void equipHand(Item item)
{
//Determine class of object to decide further actions
if (item instanceof Weapon){
this.handSlot= item;
this.damage += ((Weapon)item).getDamage();
}
else if (item instanceof Shield){
this.handSlot = item;
this.defense += ((Shield)item).getProtection();
}
}
}
class Item
{
private String name;
public Item(String name)
{
this.name = name;
}
}
class Shield extends Item
{
private int protection;
public Shield(String name, int protection){
super(name);
this.protection = protection;
}
public int getProtection(){
return protection;
}
}
class Weapon extends Item
{
private int damage;
public Weapon(String name, int damage){
super(name);
this.damage = damage;
}
public int getDamage(){
return damage;
}
}
Note that, if Weapon, Item & Shield class
have a overloaded method (for example: equip()
), I can simply use polymorphism. But in this case, the equip method is in another class. In this specific scenario, is it okay to use instanceof
operator? Or is it still a bad design?