Subtype polymorphism and arrays
- by user133466
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