w3resource

Java Polymorphism: Vehicle base class with Car and Motorcycle subclasses

Java Polymorphism: Exercise-11 with Solution

Write a Java program to create a base class Vehicle with methods startEngine() and stopEngine(). Create two subclasses Car and Motorcycle. Override the startEngine() and stopEngine() methods in each subclass to start and stop the engines differently.

Sample Solution:

Java Code:

//Vehicle.java
abstract class Vehicle {
  public abstract void startEngine();

  public abstract void stopEngine();
}

//Car.java
class Car extends Vehicle {
  @Override
  public void startEngine() {
    System.out.println("Car engine started with a key.");
  }

  @Override
  public void stopEngine() {
    System.out.println("Car engine stopped when the key was turned off.");
  }
}
//Motorcycle.java
class Motorcycle extends Vehicle {
  @Override
  public void startEngine() {
    System.out.println("Motorcycle engine started with a kick-start.");
  }

  @Override
  public void stopEngine() {
    System.out.println("Motorcycle engine stopped when ignition was turned off.");
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Vehicle car = new Car();
    Vehicle motorcycle = new Motorcycle();

    startAndStopEngine(car);
    startAndStopEngine(motorcycle);
  }

  public static void startAndStopEngine(Vehicle vehicle) {
    vehicle.startEngine();
    vehicle.stopEngine();
  }
}

Sample Output:

Car engine started with a key.
Car engine stopped when the key was turned off.
Motorcycle engine started with a kick-start.
Motorcycle engine stopped when ignition was turned off.

Explanation:

In the above exercise -

  • The "Vehicle" class is the base abstract class, and Car and Motorcycle are its concrete subclasses. Each subclass overrides the startEngine() and stopEngine() methods to provide different ways of starting and stopping the engines based on the vehicle type.
  • In the Main class, we have a static method startAndStopEngine(Vehicle vehicle) that takes an object of the base class Vehicle as a parameter. Inside this method, we call the startEngine() and stopEngine() methods on the vehicle object. Since the startAndStopEngine method takes a Vehicle type parameter, it can accept Car and Motorcycle objects,

Flowchart:

Flowchart: Vehicle Java
Flowchart: Car Java
Flowchart: Motorcycle Java
Flowchart: Main Java

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Animal base class with Lion, Tiger, and Panther subclasses.
Next: Shape base class with Circle and Cylinder subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.