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:

  1. Read name (line 1) and team size (line 2) from standard input
  2. Create Manager instance with the read values
  3. Upcast to Employee type variable (implicit)
  4. Call work() (polymorphism outputs "Managing team")
  5. Check if Manager with instanceof
  6. Downcast to Manager (explicit)
  7. 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