014-008-005
Type Casting: Upcasting and Downcasting
Medium
Problem Description
Type Casting: Upcasting and Downcasting
In this problem, you will create a program that implements an Employee (parent class) and Manager (child class), demonstrates upcasting and downcasting through polymorphism, and displays the results to standard output.
Learning Objective: Understand type conversion (casting) mechanisms in inheritance hierarchy
Overview
Two types of casting:
- Upcasting: Child → Parent class (implicit, safe)
- Downcasting: Parent → Child class (explicit, instanceof check recommended)
Specifications
Create parent class Employee:
- Private field
name - constructor accepts name
work()method: outputs "Working"getName()method: returns name
Create child class Manager:
- Extends
Employee - Private field
teamSize - Constructor accepts name and teamSize
- override
work(): outputs "Managing team" getTeamSize()method: returns teamSize
In Main class:
- Read name (line 1) and team size (line 2) from standard input
- Create Manager instance with the read values
- Upcast to Employee type variable (implicit)
- Call work() (polymorphism outputs "Managing team")
- Check if Manager with instanceof
- Downcast to Manager (explicit)
- Call getTeamSize() and output "Team size: {teamSize}"
Input Format
name
teamSize
Output Format
Managing team
Team size: {teamSize}
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