I am going through the BroCode Java tutorial on YouTube, and unfortunately I am stuck on this Polymorphism example. I created a Vehicle parent class, as well as Boat, Bicycle, and Car child classes of the Vehicle class, all with their own overloaded void go(){} methods. I wanted to stick Boat boat1, Car car1, and Bicycle bike1 into Vehicle array, then iterate through said array and call each go method in it. Please let me know what problem I am having, and thank you in advance!
Exception in thread “main” java.lang.ArrayStoreException: Car
at TestPolymorphism.main(TestPolymorphism.java:9)
I have tried playing around with the array, because I am almost positive it doesn’t like the Boat, Car, and Bicycle objects in the array, but with no luck. I tried several different way to build the array, like
Vehicles[] racers = new Vehicles[2]; Vehicles[0]=car1; Vehicles[1]=boat1; Vehicles[2]=boat2;
but the same errors have been displaying.
public class TestPolymorphism {
public static void main(String[] args) {
/*
* polymorphism is greek for 'many' 'forms', and it is the ablility of an object
* to indentify as more than one type
*/
Car car1 = new Car(); Boat boat1 = new Boat(); Bicycle bike1 = new Bicycle();
Vehicles[] racers = {car1, boat1, bike1};
for(Vehicles vehicle : racers){
vehicle.go();
}
}
}
//parent class
class Vehicles{
void go(){
System.out.println();
}
}
//child classes
class Boat extends Vehicles{
@Override
void go(){
System.out.println("boat goes");
}
}
class Car extends Vehicles{
@Override
void go(){
System.out.println("car goes");
}
}
class Bicycle extends Vehicles{
@Override
void go(){
System.out.println("bike goes");
}
}
ThatOneGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.