Computer[] labComputers = new Computer[10];
with
public class Computer {
...
void toString(){
// print computer specs
}
}
public class Notebook extends Computer{
...
void toString(){
// print computer specs + laptop color
}
}
each subscripted variable labComputers[i] can reference either a Computer object or a Notebook object because Notebook is a subclass of Computer. For the method call labComputers[i].toString(), polymorphism ensures that the correct toString method is called.
I wonder what if we do
Notebook[] labComputers = new Notebook[10];
what kind or error would I get if I reference with Computer object and a Notebook object
Since the question specifically asks about
kind of errorI will explain them with below scenariosIf you do below
Now you can only set Notebook objects in array.
Now if you do
Because arrays are
covarant,reifiedin nature ie. ifSubis a subtype ofSuper, then the array typeSub[]is a subtype ofSuper[], and arrays enforce their element types at run time it will cause ArrayStoreExceptionYou can read oracle docs about Polymorphism to know more how it works.