Search code examples
javaarraysobject

ArrayStoreException when trying to set an element of an array to a superclass object


class A {}
class B extends A {}

Hi, I'm learning Java and I'm trying to understand why this works:

A[] tab = new A[10];
tab[0] = new B();

and not this:

A[] tab = new B[10];
tab[0] = new A();

this line A[] tab = new B[10]; means that the compiler is booking 10 places for B in memory. tab[0] = new A() is setting tab[0] equal to a new A object that is smaller (?) than B (B extends A).

Why is there an ArrayStoreException: A error ? How does it work ?


Solution

  • You can store subclasses of an object, inside that object. ie B can be stored in A, but A is a superclass of type B. Basically, any class below class X in the inheritance chain can be referred to as type X, but any class above class X in the inheritance chain can NOT be referred to as type X.

    Your example

    A[] tab = new A[10]; // Perfectly fine. Equal objects.
    tab[0] = new B(); // B is a subclass of A, so this is allowed.
    
    A[] tab = new B[10]; // Same principle as above, B is a subclass of A
    tab[0] = new A(); // A is a SUPERCLASS of B, so it can not be referred to as A
    

    In short, X can only be referred to as Y, if X is a subclass of Y. (Or a subclass of a subclass. It's a recursive definition).

    Let's use some English terms

    Instead of A and B, let's have Item and Book.

    public class Item {}
    
    public class Book extends Item {}
    

    Now, it makes sense to say:

    Item b = new Book(); // All Books are items.
    

    It does not make sense to say:

    Book b = new Item(); // All items are definitely not books.