015-002-010
Upcasting and Downcasting
Hard
Problem Description
Upcasting and Downcasting
In this problem, you will create a program that reads an animal type from Scanner, creates the appropriate object, calls methods after upcasting, and performs safe downcasting using instanceof, displaying the result to standard output.
Learning Objective: Understand the behavior and safe usage of reference type upcasting and downcasting
Overview
Upcasting converts child to parent type (implicit). Downcasting converts parent to child type (explicit). Using instanceof before downcasting is safe practice.
Specifications
- Read one line from Scanner: the animal type ("Dog", "Cat", or "Animal")
- Define getType() method in Animal class
- Define getType() and fetch() methods in Dog class
- Define getType() and meow() methods in Cat class
- Assign the appropriate object to an Animal variable (upcast)
- Demonstrate getType() after upcast and instanceof-based downcast
Input Format
animal type ("Dog", "Cat", or "Animal")
Output Format
- Print
Type: [return value of getType()] - If Dog: print
Fetching! - If Cat: print
Meowing! - Otherwise: print
Unknown type
Input/Output Example
Input:
Dog
Output:
Type: Dog
Fetching!
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