i am having some trouble figuring something regarding inheritance in Java. I thought it would be straightforward but it has stumped me.
I have this superclass..
public class MyItem {
private String barCode;
private String price;
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
And i have these 2 subclasses
public class PromotionalItem extends MyItem {
private String promotion;
public String setPromotion(String promotion) {
this.promotion = promotion;
}
public void getPromotion() {
this.promotion = promotion;
}
}
public class SellableItem extends MyItem {
private String quantity;
public String setQuantity(String quantity) {
this.quantity = quantity;
}
public void getQuantity() {
this.quantity = quantity;
}
}
Now i have a method that i want to make generic, i thought something like this could work...
public void processItem(MyItem item){
if(item.getClass().isAssignableFrom(PromotionalItem.class)){
processPromotionalItem((PromotionalItem)item);
}
else{
processSellableItem((SellableItem)item);
}
}
But I am getting a ClassCastException when i try to cast these items as their respective subclasses. I thought something like this would be do-able. Am i missing something? What is the alternative do something like this?