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(CarorBicycle) andnameseparated by a space
Specifications
Vehicle class
- Has a
String namefield - constructor initializes
name describe()method returns"Vehicle: " + name
Car class (extends Vehicle)
- Constructor passes
nametosuper honk()method returnsname + " honks!"
Bicycle class (extends Vehicle)
- Constructor passes
nametosuper ringBell()method returnsname + " rings bell!"
Main class
- Read input with Scanner and build a
Vehicle[]array - Create a
Carinstance when type isCar, aBicycleinstance when type isBicycle - Loop through the array, for each element:
- Print the result of
describe() - If it is a
Carinstance, print the result ofhonk() - If it is a
Bicycleinstance, print the result ofringBell()
- Print the result of
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