java - Use instanceof or public method to get instance -


so have 3 classes:

  • item
  • groupitem extends item
  • productitem extends item

i passing array of item objects class , want separate things depending on class type.

would using instanceof acceptable way of doing or should have internal boolean isgroup() method set on initialisation of specified sub-class.

 class item {       protected boolean isgroup = false;       public boolean isgroupitem() { return isgroup; }  }   class groupitem extends item {       public groupitem() {            isgroup = true;       }  }   class productitem extends item {       public productitem() {            isgroup = false;       }  }    class promotion {       // item can either group or list of items       private list<item> items = new linkedlist<item>;       public void additem(item itemobj) {            items.additem(itemobj);       }       public list<item> getitems() {            return items;       }  }     class checker {       // items retrieved promotion , passed class array       public checker(item[] items) {            // either             if(items[0] instanceof groupitem) {                 // ...            }             // or             if(items[0].isgroupitem()) {                 // ...            }        }  } 

so questions are:

  • instanceof or method?
  • if method, in item or promotion?
  • and, why? (just can better understand reasoning)

thanks in advance

this exact place should use instanceof operator .

the instanceof operator compares object specified type. can use test if object instance of class, instance of subclass, or instance of class implements particular interface.

there no point skatch new method or boolean property stuff. can identify specific object of groupitem check instanceof.

you can use groupitem.class.isinstance(items[0]) check same. -

if(groupitem.class.isinstance(items[0])) {       // ... } 

Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -