To make the explanation easier I’ll give a quick overview of the program. I’m supposed to create an “online book store.” I have abstract class Item and 2 subclasses, Apparel and Textbooks. In the main the user will first “fill” the store with either textbooks or apparel and then “sell” items, given they’re in stock.
In the main I created an array of Item (abstract) that will hold objects of both Textbook and Apparel types, acting like the “store”. My problem comes in when trying to access the array.
When “selling” an item, the user, for example, inputs the title of the book they want to purchase. I have to validate that this title is “in stock” (i.e. in the Item array)
This is my method for buying the book (i is the # of items in the store, store is the abstract array, and its not complete as you can see. I’m stuck on the if statement)
public static void buyBook(Item[] store, int i)
{
TextBook book = new TextBook();
String title;
title = JOptionPane.showInputDialog("Book title: ");
for(int j = 0; j < i; j++)
{
if(store[j] instanceof TextBook)
{
if()
}
}
My idea is to compare title (the user’s input) to those of Textbook type in store (abstract array)
I know its wrong but something like:
store[j].getTitle().compareTo(title)
BUT of course store[j] can’t access getTitle (because its in TextBook, the subclass)
And now I’m completely stuck. Some guidance would be appreciated.
Downcast is your friend.
((TextBook)store[j]).getTitle().compareTo(title)Also, why not use for-each?for (Item item : store) if (item instanceof TextBook) ...