015-002-004

Upcasting: From Subclass to Superclass

Medium

Problem Description

Upcasting: From Subclass to Superclass

In this problem, you will create a program that defines a Vehicle class and its Car subclass, reads a vehicle name from standard input, assigns a Car instance to a Vehicle type variable via upcasting, calls the move() method, and displays the result to standard output.

Learning Objective: Understand upcasting where a subclass instance is assigned to a superclass type variable

Overview

Create a Vehicle class and its subclass Car, then use upcasting to store in different type variables.

Specifications

  • Vehicle class: has a name field initialized in the constructor. move() method outputs "{name} is moving"
  • Car class: extends Vehicle, calls super(name) in the constructor. Overrides move() to output "{name} is driving"
  • Read a vehicle name from standard input and assign a Car instance to a Vehicle type variable (upcasting)

Input

One line with the vehicle name (string).

Output Format

{name} is driving

If the input is Toyota:

Toyota is driving

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