Today I’ve written simple test about syntax of declaring array, so, there are 3 classes:
public class A {
}
public class B extends A {
}
public class C extends A {
}
and I’ve tried to create array using next syntax
A[] aa = new B[10];
So, It is possible, but we can added just instances of class B to this array , If you will try to add instances of A or C you receive java.lang.ArrayStoreException and question, Why can we create array using syntax like that and where is it can be used and make some profit ?
Thanks.
The reason this syntax is allowed in the language is that sometimes you don’t care what subclass of objects are in the array. The Java Language Specification rules for array subtyping include:
(where >1 means “direct subtype”).
This allows one to write a method like this:
and then call it with:
This language feature does have the unfortunate effect of deferring ArrayStoreException problems to run time.