Vehicle [ ] acme = new Vehicle [5];
acme[0] = new LightTruck(111, "Elmer Fudd", "GM", 500);
acme[1] = new Car(222, "Wile E Coyote", "Ferrari", 2, 10);
acme[2] = new Passenger(333, "Foghorn Leghorn", "Toyota", 5);
acme[3] = new Commercial(444, "Daffy Duck", "Mack", 42000);
acme[4] = new Vehicle(555, "The Roadrunner", "Honda");
for(int i = 0; i < acme.length; i++)
{
System.out.println(acme[i].toString() + "\n");
}
acme[0].changeCapacity(250); //ERRORS HERE
In the above code, LightTruck/Car/Etc extends Vehicle.
All the classes have their own toString method which print different things.
LightTruck has a method called changeCapacity.
The loop works and all the different toString methods return different values according to how its defined in the subclass (including private instance variables from the subclass).
But why does changeCapacity not work and errors? The error log seems to suggest that it is because the compiler checks the Vehicle class for the changeCapacity method, but if thats true, then how come toString works? Wouldn't toString() simply return what is only in the Vehicle method?