015-004-005

Polymorphism: Return Values

Hard

Problem Description

polymorphism: Return Values

In this problem, you will create a program that implements a createVehicle(boolean needsEngine) factory method returning Car or Bike objects as a Vehicle type based on boolean values read from standard input, then calls getType() on each returned object and displays the vehicle type to standard output.

Learning Objective: Understand how to use parent class type as return value and return different subclass objects

Overview

You have Car and Bike classes that inherit from Vehicle class. Implement a factory method that returns different vehicle objects based on conditions.

Specifications

  • Vehicle class: getType() method (returns "Unknown")
  • Car class: getType() returns "Car"
  • Bike class: getType() returns "Bike"
  • createVehicle(boolean needsEngine) method: Returns Car if argument is true, Bike if false (return type is Vehicle)
  • Read input with Scanner, create N vehicles, and output their types

Input Format

N
needsEngine_1
needsEngine_2
...
needsEngine_N
  • First line: number of vehicles N
  • Next N lines: whether each vehicle needs an engine (true or false)

Output Format

N lines, each containing the type of the corresponding vehicle

Sample Input/Output

Input:
2
true
false

Output:
Car
Bike

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up