Design a simple vehicle hierarchy with a base class 'Vehicle' and two subclasses 'Car' and 'Motorcycle'. The 'Vehicle' class should have properties 'brand' and 'year'. 'Car' should add a 'numDoors' property, while 'Motorcycle' should add a 'hasSidecar' property. Implement appropriate constructors and a 'displayInfo()' method for each class. Create instances based on user input and display their information. Input: Read three lines containing the vehicle type ("Car" or "Motorcycle"), brand, and year. For Car, also read the number of doors. For Motorcycle, read a boolean indicating if it has a sidecar. Output: Print the vehicle information using the displayInfo() method.
Computer scienceProgramming languagesJavaCode organizationObject-oriented programmingClass hierarchiesBuilding class hierarchies
Inheritance
Wheels of inheritance: Vrooming OOP
Report a typo
Sample Input 1:
Car
Toyota
2022
4Sample Output 1:
Toyota (2022)
Number of doors: 4Sample Input 2:
Motorcycle
Harley
2021
trueSample Output 2:
Harley (2021)
Has sidecar: trueWrite a program in Java 17
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// TODO: Implement the Vehicle class
// TODO: Implement the Car class (extends Vehicle)
// TODO: Implement the Motorcycle class (extends Vehicle)
// Read input and create appropriate vehicle object
String vehicleType = scanner.nextLine();
String brand = scanner.nextLine();
int year = Integer.parseInt(scanner.nextLine());
if (vehicleType.equals("Car")) {
int numDoors = Integer.parseInt(scanner.nextLine());
// TODO: Create a Car object and call displayInfo()
} else if (vehicleType.equals("Motorcycle")) {
boolean hasSidecar = Boolean.parseBoolean(scanner.nextLine());
// TODO: Create a Motorcycle object and call displayInfo()
}
scanner.close();
}
}
Create a free account to access the full topic
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.