Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting

One Employee variable e points at Arun, then Emma (a Manager), then Lucas (a Developer), and the same e.work() gives three answers. One loop over Employee[] replaces a growing if-else chain, and instanceof plus a cast reaches holdMeeting().

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Store a child object in a parent reference (upcasting)
  • Explain dynamic dispatch: the object, not the variable, decides which method runs
  • Replace an if-else type chain with one loop over a parent-typed array
  • Use instanceof and a cast to reach a child's own method safely

Before you start

  • Java method overriding and the Object class

Polymorphism means "many forms": one call takes a different form depending on the object. Think of a universal remote. There's one Play button, and the TV and the music system each play in their own way.

The problem: every new class adds a branch

Imagine a method that describes an employee by checking its type: if it's a Manager, say it leads people; otherwise say it works. Add a Developer class and you reopen the method for another branch. Add a Director, another branch. The chain grows with every class. With polymorphism the whole thing becomes one call, e.work(), and each object brings its own version. The classes are the Employee family from method overriding.

The same e, a different object

package org.studyeasy.s03l12;

public class Ex01_Upcasting {
    public static void main(String[] args) {
        Employee e = new Employee("Arun", 60000);
        System.out.println(e.work());        // Employee's version

        e = new Manager("Emma", 95000, 6);   // upcast
        System.out.println(e.work());        // Manager's version

        e = new Developer("Lucas", 80000, "Java");
        System.out.println(e.work());        // Developer's version
    }
}
Arun is working
Emma is working and leads 6 people
Lucas is writing Java

Putting a Manager object into an Employee variable is upcasting. It's automatic and safe, because a Manager is an Employee. The other way round isn't: Manager m = new Employee("Arun", 60000); is "incompatible types". Same variable, same line, three answers.

One reference, Employee e, can point at three objects: Arun an Employee, Emma a Manager, Lucas a Developer. The call e.work() follows the arrow to whichever object e points at, and that object's work() runs. The variable's type never changes; the object decides. Employee e Arun: Employee Emma: Manager Lucas: Developer "Arun is working" "Emma is working and leads 6 people" "Lucas is writing Java"
Dynamic dispatch: the object e points at decides which work() runs, at run time.

The type of e never changes. The object it points at decides which work() runs, and that's decided while the program runs. This is called dynamic dispatch.

One loop, no type checks

package org.studyeasy.s03l12;

public class Ex02_StaffLoop {
    public static void main(String[] args) {
        Employee[] staff = {
            new Employee("Arun", 60000),
            new Manager("Emma", 95000, 6),
            new Developer("Lucas", 80000, "Java"),
            new Director("Priya", 150000, 40, "Sales")
        };

        for (Employee e : staff) {          // one loop, no if-chain
            System.out.println(e.work());
        }
    }
}
Arun is working
Emma is working and leads 6 people
Lucas is writing Java
Priya is working and leads 40 people

One Employee array holds four kinds of object; they all fit because each one is an Employee. One call, four answers, no if. Priya is a Director with no work() of her own, so Java climbs to Manager's version. Add another kind of employee to the array and the loop doesn't change at all. In a large application, that's a big deal.

instanceof first, then cast

Through an Employee variable you can only call methods Employee has. e.holdMeeting() is "cannot find symbol", even when the object really is a Manager. The variable's type limits what you may call.

package org.studyeasy.s03l12;

public class Ex03_Downcasting {
    public static void main(String[] args) {
        Employee[] staff = {
            new Employee("Arun", 60000),
            new Manager("Emma", 95000, 6),
            new Developer("Lucas", 80000, "Java"),
            new Director("Priya", 150000, 40, "Sales")
        };

        for (Employee e : staff) {
            System.out.println(e.work());
            if (e instanceof Manager) {     // check first, then cast
                Manager m = (Manager) e;
                System.out.println(m.holdMeeting());
            }
        }
    }
}
Arun is working
Emma is working and leads 6 people
Emma meets a team of 6
Lucas is writing Java
Priya is working and leads 40 people
Priya meets a team of 40

instanceof asks the object (not the variable) "are you a Manager?". Emma is, and so is Priya, because a Director is a Manager. Then (Manager) e is a downcast: it gives a second reference, m, of type Manager, pointing at the same object, and holdMeeting() opens up. Arun and Lucas skip the block. Modern Java shortens this check-and-cast into one step; see pattern matching for instanceof.

Recap

TermMeaning
Upcastingchild object in a parent reference; automatic and safe
Dynamic dispatchthe object's own method runs, decided at run time
instanceofasks which class the object really is
Downcastinga cast to reach the child's own methods, only after the check

The reference type decides what you may call; the object decides what runs.

Keep going in Java · 34 of 79

Previous
Java Method Overriding, @Override and the Object Class
Next post
Java Composition: Has-A vs Is-A
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • The problem: every new class adds a branch
  • The same e, a different object
  • One loop, no type checks
  • instanceof first, then cast
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.