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:
- Create Manager instance (name: "Alice", teamSize: 5)
- 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: 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?
