Storing same type but still getting an ArrayStoreException
- by Firefoxx Pwnass
I have strange problem. I have three classes. Book ( abstract ), and two subclasses ( Fiction, Nonfiction). I have created array of Book references. That array can hold both subclasse's objects. I'have following code for Fiction class.
public class Fiction extends Book{
public Fiction(String title) {
super(title);
setPrice();
}
public void setPrice() {
super.price = 24.99;
}
}
And the "same" code for Nonfiction class
public class Nonfiction extends Book{
public Nonfiction(String title) {
super(title);
setPrice();
}
public void setPrice() {
super.price = 37.99;
}
}
And this is Main program.
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
Book[] book = new Fiction[6];
for(int i = 0; i<book.length; i++) {
if(i<4) {
String title = JOptionPane.showInputDialog("Enter fiction book, no "+i);
book[i] = new Fiction(title);
} else {
String title = JOptionPane.showInputDialog("Enter non fiction book, no "+i);
book[i] = new Nonfiction(title);
}
}
for(int x = 0; x<book.length; x++) {
System.out.println("Book named "+book[x].getTitle()+" costs "+book[x].getPrice());
}
}
}
For any reason i'm getting ArrayStoreException on this line..
book[i] = new Nonfiction(title);
But same code works for Fiction class. I checked java documentation and it says that this exception is thrown when i'm trying to store different objects in array ( like String and Int ), but in this case they are all the same objects. Both classes are children of superclass, that means, they are of the same type. I'm confsued. A little help here please?