015-002-007

Handle Animals with Upcasting

Easy

Problem Description

Handle Animals with Upcasting

In this problem, you will create a program that defines a name field and speak() method in an Animal parent class, overrides it in a Dog subclass, reads a name from Scanner, assigns a Dog instance to an Animal type variable (upcasting), calls the method, and displays the result to standard output.

Learning Objective: Understand the basics of polymorphism through upcasting

Overview

Define a name field, constructor, and speak() method in the Animal class, then override the constructor and speak() in the Dog class. In the Main class, read a name from Scanner, assign a Dog instance to an Animal type variable, and call speak() to confirm that the runtime type's (Dog's) method is executed.

Specifications

  • Create an Animal class (Animal.java):
    • Has a protected String name field
    • Animal(String name) constructor initializes the field
    • speak() method outputs name + " speaks"
  • Create a Dog class (Dog.java): Extends Animal
    • Dog(String name) constructor calls super(name)
    • Overrides speak() to output name + " barks"
  • Main class:
    • Read one line (animal name) from Scanner
    • Upcast with Animal animal = new Dog(name);
    • Call animal.speak()

Input

Animal name (one line)

Output Format

{name} barks

Example

Input: Buddy
Output: Buddy barks

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