w3resource

Java: Abstract Vehicle Class with Car and Motorcycle Subclasses

Java Abstract Class: Exercise-7 with Solution

Write a Java program to create an abstract class Vehicle with abstract methods startEngine() and stopEngine(). Create subclasses Car and Motorcycle that extend the Vehicle class and implement the respective methods to start and stop the engines for each vehicle type.

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: Starting the engine...");
  }

  @Override
  public void stopEngine() {
    System.out.println("Car: Stopping the engine...");
  }
}
//Motorcycle.java
class Motorcycle extends Vehicle {
  @Override
  public void startEngine() {
    System.out.println("Motorcycle: Starting the engine...");
  }

  @Override
  public void stopEngine() {
    System.out.println("Motorcycle: Stopping the engine...");
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Vehicle car = new Car();
    Vehicle motorcycle = new Motorcycle();

    car.startEngine();
    car.stopEngine();

    motorcycle.startEngine();
    motorcycle.stopEngine();
  }
}

Sample Output:

Car: Starting the engine...
Car: Stopping the engine...
Motorcycle: Starting the engine...
Motorcycle: Stopping the engine...

Explanation:

In the above exercise -

  • The abstract class "Vehicle" has two abstract methods: startEngine() and stopEngine(). The subclasses Car and Motorcycle extend the "Vehicle" class and provide their own implementations for these abstract methods.
  • The "Car" class starts and stops the car's engine, while the Motorcycle class starts and stops the motorcycle's engine.
  • In the main method, we create instances of Car and Motorcycle. We then call the startEngine() and stopEngine() methods on each object to start and stop the engines for both vehicle types.

Flowchart:

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

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Abstract Shape3D Class with Sphere and Cube Subclasses.
Next: Java: Abstract Person Class with Athlete and LazyPerson Subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.