When array is created it remembers what type of data it is meant to store. So if you have classes
class Employee { .. }
class Manager extends Employee { .. }
and you will create array
Manager[] arrM = new Manager[10];
array will remember that it need to store only instances of Manager class or its derived types. But such array can't store super type of Manager since super type may not have all methods or fields of Manager class so something like
arrM[0] = new Manager();
is OK, but
arrM[0] = new Employee();
throws java.lang.ArrayStoreException: Employee
pointing that Employee is not correct argument here.
So in your case you are
creating array for Managers
Manager[] mans ={new Manager("Adam"),new Manager("Ben")};
creating reference to this array using its super-type Employee
Employee[] emps =mans;
(but this reference it still pointing to array which can hold only Menagers)
and trying to place into array new Employee
emps[0] = new Employee("Charlie");
but as I mentioned this can't be allowed because it is possible that Employee do not have same members as Manager. Lets say Menager can hire(...)
someone, while Employee can't (doesn't have this method). What would happen if you would call
mans[0].hire(new Employee("Tom");
and emps[0] = new Employee ("Charlie");
would not throw exception but would let you place Employee in emps[0]
? Since mans
and emps
are using same array it would mean that mans[0].hire(new Employee("Tom")
would be called from Employee("Charlie")
which can't hire anyone because Employee don't have hire
method.
That is why you can't place instance of super-type (Employee) in array of Managers.