Storing same type but still getting an ArrayStoreException
Posted
by
Firefoxx Pwnass
on Stack Overflow
See other posts from Stack Overflow
or by Firefoxx Pwnass
Published on 2012-09-28T15:35:23Z
Indexed on
2012/09/28
15:37 UTC
Read the original article
Hit count: 152
java
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?
© Stack Overflow or respective owner