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.