014-008-005

Type Casting: Upcasting and Downcasting

Medium

Problem Description

Type Casting: Upcasting and Downcasting

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. Create Manager instance (name: "Alice", teamSize: 5)
  2. Upcast to Employee type variable (implicit)
  3. Call work() (polymorphism outputs "Managing team")
  4. Check if Manager with instanceof
  5. Downcast to Manager (explicit)
  6. Call getTeamSize() and output "Team size: 5"

Output Format

Managing team
Team size: 5

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?