Warum sollte bei der Ausführung dieses Codes ein Laufzeitfehler auftreten? Das Array ist so definiert, dass es Früchte enthält, aber wie kann ich es nicht fruchtbar machen, nachdem ich es mit Apfel initialisiert habe?Runtime-Upcasting-Fehler von Thinking in Java
class Fruit{}
class Apple extends Fruit{}
class Jonathan extends Apple{}
class Orange extends Fruit{}
public class CovariantArrays {
public static void main(String[] args) {
Fruit[] fruit = new Apple[10];
fruit[0] = new Apple();
fruit[1] = new Jonathan();
try {
fruit[0] = new Fruit();
} catch(Exception e) { System.out.println(e); }
try {
fruit[0] = new Orange();
} catch(Exception e) { System.out.println(e); }
}
}
Das Array ist ein 'Apple []'. Warum würdest du erwarten, dass es in der Lage ist, etwas zu halten, das keine Art von "Apple" ist? –