Question

I have a java program that simulates a store. I have a Product class with 3 child classes (Game, Book, and Movie). I have an array of Products, and I want to do something with each item in the array depending on what particular type of child class it is.

The problem I am having is that the array is an array of Products and, as such, items from it cannot invoke functions of the child classes, even though each "Product" in the array actually is one of the three child classes.

How do I fix this? I know I can put a bunch of abstract functions into the Product class that are overridden in the child classes, but I was wondering if there was an easier way of doing this.

Was it helpful?

Solution

If you want to use different functions for each child class you just have to use the "instanceof" operator and type casting like so:

For example somewhere in a loop:

if(items[i] instanceof Game) {
   Game g = (Game)items[i];
   g.SomeGameSpecificFunc();
} else if(items[i] instanceof Book) {
   //...
}

You can also get a string with a name of the class of current object through reflection, but this is rather slow:

String className = items[i].getClass().toString();

//in Java 7+
switch(className) {
   case "Book":
      //do something
      break;
      //etc
}

But you should use these techniques only if you really really have to use functions with different names and parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top