Hello, I was practicing polymorphism messing around with a Car analogy when I came across a problem. In my main method within my for loop, I tried to access my starteEngine(), accelerate(), and brake() methods yet I would get an error. I have since fixed it and found out that it worked once I switched it from "void" to String and returned the string. But I want to know why it wouldn't work as it is below. I thought that with void since it's not returning anything, it would simply execute the output line, and by accessing it as I tried in the for loop within my main method, it would simply output as well. That wasn't the case, so my question is if anyone could explain this to me? Thank you.
// 06.03.2021 //Polymorphism class CarP { //Fields private boolean engine; private int cylinders; private int wheels; private int doors; private String color; private String name; //Constructor public CarP(int cylinders, String name, int doors, String color) { this.wheels = 4; this.engine = true; this.cylinders = cylinders; this.name = name; this.doors = doors; this.color = color; } //Methods public void startEngine() { System.out.println("Starting engine."); } public void accelerate() { System.out.println("Accelerating."); } public void brake() { System.out.println("Breaking."); } //Getters and Setters public int getCylinders() { return cylinders; } public void setCylinders(int cylinders) { this.cylinders = cylinders; } public int getDoors() { return doors; } public void setDoors(int doors) { this.doors = doors; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getName() { return name; } public void setName(String name) { this.name = name; } }//end Car class DodgeCharger extends CarP{ public DodgeCharger() { super(8, "Dodge Charger", 4, "Mute black"); } } class DodgeChallenger extends CarP{ public DodgeChallenger() { super(8, "Dodge Challenger", 2, "Mute black"); } } class ToyotaSupra extends CarP{ public ToyotaSupra() { super(6, "Toyota Supra", 2, "White"); } } public class CarV2 { public static void main(String[] args) { for(int i = 1; i < 6; i++) { CarP car = randomCar(); System.out.println("Car #" + i + " : " + car.getName() + "\nCar Color: " + car.getColor() + "\nCylinders: " + car.getCylinders() + "\nNumber of doors: " + car.getDoors() + "\n" + car.startEngine() + "\n " + car.accelerate() + "\n" + car.brake() + "\n"); } }//end main public static CarP randomCar() { int randomNumber = (int)(Math.random() * 3) +1; System.out.println("Random number generated was: " + randomNumber); switch(randomNumber) { case 1: return new DodgeCharger(); case 2: return new DodgeChallenger(); case 3: return new ToyotaSupra(); } return null; }//end randomMovie() }//end class