I was given 2 classes for the assignment: Sale and DiscountSale (which extends Sale). I'm supposed to create a new class called MultiItemSale which will create an array (shopping cart) of both Sale and DiscountSale objects. But I can't get methods from DiscountSale to work on DiscountSale ojbects within the array.
class Sale (the base class) has some methods, setName() and setPrice() in particular.
class DiscountSale extends Sale, so it can use setName() and setPrice(), but it also has setDiscount() among other things.
in MultiItemSale:
Sale[] shoppingCart = new Sale[numOfItems];
From my understanding, since DiscountSale extends Sale, both Sale and Discount Sale objects should be able to placed within this array, correct?
I use a for loop to ask if an item is discounted. If it isn't then:
shoppingCart[i] = new Sale();
if it is discounted:
shoppingCart[i] = new DiscountSale();
And this is where I begin to run into issues:
The following works, because setName() and setPrice() are from the Sale class
Also, this is all under an if-statement that says if item is discounted, then:
shoppingCart[i] = new DiscountSale();
shoppingCart[i].setName(name);
shoppingCart[i].setPrice(price);
But if I try to do this I get errors because setDiscount() is from DiscountSale:
shoppingCart[i].setDiscount(discount);
Eclipse tells me, "The method setDiscount(double) is undefined for the type Sale". If
shoppingCart[i] = new DiscountSale();
why can't I use a method from DiscountSale on that object? I think I have a misunderstanding of how polymorphism and arrays work.