Upcasting in Java
beginner· OOP · Inheritance
Problem
Upcasting means storing a subclass object in a variable declared with a parent type — Java allows this automatically, since every subclass object is guaranteed to support everything the parent type promises.
Assign a Manager object to an Employee-typed variable, and show that only Employee's own members are reachable through it.
Input
Employee e = new Manager();
Output
Employee is working
Java Program
Java
class Employee {
void work() {
System.out.println("Employee is working");
}
}
class Manager extends Employee {
void manageTeam() {
System.out.println("Manager is managing the team");
}
}
public class UpcastingDemo {
public static void main(String[] args) {
Employee e = new Manager(); // implicit upcast — no cast syntax needed
e.work();
// e.manageTeam(); would not compile: Employee's type doesn't declare manageTeam()
}
}Output
Employee is working
Core Logic
Declaring the variable as the parent type while assigning a subclass instance to it happens automatically in Java, with no cast needed.
How It Works
- 1
Employee e = new Manager();upcasts implicitly — no explicit cast syntax is written, since going from a subclass to its parent is always safe. - 2
e's declared type isEmployee, even though the object it actually refers to is aManager. - 3Calling
e.work()works fine, sincework()is declared onEmployeeitself. - 4A call like
e.manageTeam()would fail to compile —manageTeam()only exists onManager, and the compiler only allows calls that the declared typeEmployeeactually promises.
Even though
e refers to an actual Manager object, e.work() prints "Employee is working", since Manager doesn't override work() here.💡
Key Point: Upcasting narrows what's accessible through a reference, not what the object actually is — the underlying object is still fully a Manager, but the Employee-typed reference can only see Employee's own members.
Key Concepts
upcastingimplicit conversionreference type vs. actual type