My problem is as following:
I have an abstract class called Product and 2+ subclasses called Book and Magazine. Magazine has 1 extra method that isn't found in Product or Book.
So far so good. But I want to store these different products in 1 array like so:
List<Product> products = new ArrayList<>();
products.add(new Book());
products.add(new Magazine());
Still no problems right? However at this point I also want to do this(index 1 is a Magazine):
products.get(1).magazineMethod()
And this is where everything falls flat. I know of instanceof and how that would solve my problem. However upon googling and looking on stackoverflow it seems that using instanceof in this matter is bad. For every different Product subclass I would have to add another check with instanceof. I asked my teacher about this and he couldn't give me a proper answer and told me he would check it out.
I know how polymorphism works where if the Product also had magazineMethod() it would work. But that makes no sense since a Product isn't a Magazine and doing that would defeat the whole point of inheritance.
And yes, this is part of homework but the question in my mind is so fundamental that I'd like the proper solution to this instead of some workaround/hackjob.
Fundamentally, you cannot. If your variable is of type Foo, you can only use functions on Foo or Foo's parents.
Workarounds:
Before passing the magazine to the array, also store it in a variable of type Magazine, and refer to that variable when using magazine functions
Cast the product to Magazine before calling
instead of magazineMethod(), have a generic method that applies to both books and magazines, with the behavior overridden by the subclass.
The third option is generally best.