015-003-007

Downcast: instanceof Check

Medium

Problem Description

Downcast: instanceof Check

In this problem, you will read vehicle types and names from standard input, store Car and Bicycle objects in a Vehicle[] array, check each element's type using instanceof, safely downcast it, and call subclass-specific methods to display the result to standard output.

Learning Objective: Understand how to perform safe downcasting after type checking with instanceof

Overview

Create a superclass Vehicle with subclasses Car and Bicycle. Read vehicle data from standard input, store them in a superclass-typed array, check types using instanceof, then downcast to call subclass-specific methods.

Input Format

N
type1 name1
type2 name2
...
  • Line 1: number of vehicles N
  • Next N lines: type (Car or Bicycle) and name separated by a space

Specifications

Vehicle class

  • Has a String name field
  • constructor initializes name
  • describe() method returns "Vehicle: " + name

Car class (extends Vehicle)

  • Constructor passes name to super
  • honk() method returns name + " honks!"

Bicycle class (extends Vehicle)

  • Constructor passes name to super
  • ringBell() method returns name + " rings bell!"

Main class

  • Read input with Scanner and build a Vehicle[] array
  • Create a Car instance when type is Car, a Bicycle instance when type is Bicycle
  • Loop through the array, for each element:
    • Print the result of describe()
    • If it is a Car instance, print the result of honk()
    • If it is a Bicycle instance, print the result of ringBell()

Sample I/O

Input

2
Car Sedan
Bicycle Mountain

Output

Vehicle: Sedan
Sedan honks!
Vehicle: Mountain
Mountain rings bell!

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