Subtype polymorphism and arrays
Posted
by
user133466
on Stack Overflow
See other posts from Stack Overflow
or by user133466
Published on 2012-10-14T02:44:44Z
Indexed on
2012/10/14
3:37 UTC
Read the original article
Hit count: 147
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
© Stack Overflow or respective owner