Java Polymorphism and Dynamic Binding: How Method Calls Are Resolved
Understand polymorphism in Java: the is-a rule and substitution principle, declared vs actual types, why arrays are covariant and throw ArrayStoreException, the exact steps of a method call (overload resolution, static vs dynamic binding, method tables), covariant return types and override rules.
kvi5hnuCode Sprout team member12 min readOn this page
In the previous article, a loop over an Employee[] array called e.getSalary() and got the manager's bonus included automatically. This article explains why that works: polymorphism (a variable can refer to objects of different types) and dynamic binding (the method is selected at runtime). You'll also see exactly how the compiler and the JVM resolve every method call. Knowing this answers many tricky interview questions.
The "Is-A" Rule and Substitution
Before writing extends, ask whether the sentence "every subclass is a superclass" is true. "Every manager is an employee" holds, so Manager extends Employee is sound. The sentence doesn't work backwards, and it doesn't need to: plenty of employees aren't managers.
The practical consequence is substitutability. Any place that accepts an Employee must also accept a Manager, including a variable of type Employee:
Employee e;
e = new Employee(. . .); // Employee object expected
e = new Manager(. . .); // OK, a Manager can be used as well
In Java, object variables are polymorphic. A variable of type Employee can refer to an Employee object or to an object of any subclass of Employee (Manager, Director, Accountant, and so on).
(The formal version of this idea, the Liskov Substitution Principle, is the "L" in SOLID. A subclass must honor the superclass's contract, so that code written for the superclass keeps working.)
Declared Type vs. Actual Type
Every object variable has two types:
- the declared (static) type, written in the declaration and known to the compiler, and
- the actual (runtime) type: the class of the object it currently refers to, known to the JVM.
Manager boss = new Manager(. . .);
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[0] and boss refer to the same object. But the compiler considers staff[0] only an Employee, because that's its declared type. So
boss.setBonus(6500); // OK
staff[0].setBonus(6500); // ERROR: cannot find symbol
The second call fails because setBonus isn't a method of Employee. The declared type decides which methods you may call. The actual type decides which implementation runs.
You also can't assign a superclass reference to a subclass variable:
Manager m = staff[i]; // ERROR: incompatible types: Employee cannot be converted to Manager
The compiler can't prove that staff[i] holds a manager, and if it held an ordinary employee, m.setBonus(...) would be calling a method the object lacks. (When you know an Employee variable refers to a Manager, you can cast; see casting and pattern matching.)
The array trap: covariance and ArrayStoreException
Java lets you convert an array of subclass references to an array of superclass references without a cast:
Manager[] managers = new Manager[10];
Employee[] staff = managers; // OK: arrays are covariant
Reading through staff is safe, because every manager is an employee. Writing is the problem. staff and managers are two names for one array, and the compiler only checks staff's declared type, so this compiles:
staff[0] = new Employee("Omar Haddad", . . .);
If it were allowed, managers[0] would now hold an object without a bonus field, and managers[0].setBonus(1000) would break.
Java closes the hole at run time. An array object knows the element type it was created with (Manager here), and every store into it is checked against that type. A mismatch throws ArrayStoreException:
ArrayStoreException: Employee
Generic collections such as ArrayList<Manager> are not covariant (an ArrayList<Manager> isn't an ArrayList<Employee>), so they catch this at compile time. This is one reason to prefer collections over arrays; see the generics part.
How a Method Call Is Resolved
A call x.f(args), where x is declared with class C, is handled partly by javac and partly by the JVM.
Step 1: Gather candidates (compile time)
javac starts from the declared type C. It gathers every method named f declared in C, plus every accessible f that C inherits. A private method in a superclass doesn't qualify. The result may contain several overloads, say f(int) and f(String).
Step 2: Pick the overload (compile time)
javac then compares the argument types with each candidate's parameters and keeps the most specific match; this is overload resolution. With a String argument, f(String) wins over f(int). Widening (int to double), subtype conversion (Manager to Employee), boxing and varargs make the rules longer, but the outcome is the same: exactly one method, or a compile error if there is none or the choice is ambiguous. (The phases are described in the overloading article.)
At this point the signature is fixed: the method's name plus its parameter types.
Step 3: Static or dynamic binding?
Some methods can't be overridden: private, static and final methods, and constructors. For these, the signature already identifies one implementation, and the call is bound at compile time (static binding). For every other instance method, the implementation depends on the object's actual class, so the decision is left to the JVM (dynamic binding). For x.f("Hello"), the bytecode says "call f(String) on whatever x is".
Step 4: Dynamic binding (run time)
Suppose x currently refers to an object of class D, a subclass of C. Conceptually, the JVM looks for f(String) in D; if D doesn't declare it, it tries D's superclass, then the next one up, until it finds an implementation.
Walking the hierarchy on every call would be wasteful, so JVMs typically build a dispatch table (often called a vtable) for each class when it is loaded: for every overridable signature, which class's code to run. A subclass's table starts as a copy of its superclass's table, with overridden entries replaced and new methods appended. A call then costs one lookup. A super.f(...) call is the exception: it is bound to the superclass's implementation directly.
For Employee and Manager, leaving out what comes from Object, the tables look like this:

Employee:
getName() -> Employee.getName()
getSalary() -> Employee.getSalary()
getStartDate() -> Employee.getStartDate()
giveRaise(double) -> Employee.giveRaise(double)
Manager:
getName() -> Employee.getName()
getSalary() -> Manager.getSalary() (overridden)
getStartDate() -> Employee.getStartDate()
giveRaise(double) -> Employee.giveRaise(double)
setBonus(double) -> Manager.setBonus(double) (added)
So for e.getSalary() the JVM takes the table of e's actual class, reads the getSalary() entry, and jumps to that code. Which class e was declared with plays no role at this stage.
(Modern JVMs go further. The JIT compiler notices when a call site always sees the same class and inlines the method, so dynamic binding usually costs almost nothing.)
Why dynamic binding matters
Because the choice happens at run time, you can add subclasses without touching code that already works. Introduce a Contractor extends Employee next year, and the existing loop calling e.getSalary() handles contractors correctly without even being recompiled. This "open for extension, closed for modification" property (the "O" in SOLID) is a big reason object-oriented code scales.
Rules for Overriding
A method in a subclass overrides a superclass method when it has the same signature (name and parameter types). The return type isn't part of the signature, but it must be compatible:
Covariant return types
An overriding method may narrow the return type to a subtype. Say every employee names a stand-in for holidays:
public Employee getStandIn() { . . . }
A manager's stand-in must be able to approve things, so it should itself be a manager. Manager can declare exactly that:
@Override
public Manager getStandIn() { . . . } // OK: Manager is a subtype of Employee
The two methods have covariant return types. Callers holding a Manager get a Manager back without a cast. Primitive return types must match exactly: overriding int g() with long g() fails with return type long is not compatible with int.
Access can't be weaker
An override may keep or widen the access level, never reduce it, since callers holding an Employee reference must still be allowed to call the method. Leaving out public by accident is the usual way to hit this:
class Employee { public double getSalary() { . . . } }
class Manager extends Employee {
double getSalary() { . . . } // error: getSalary() in Manager cannot override getSalary() in Employee
} // attempting to assign weaker access privileges; was public
Static methods and fields aren't polymorphic
Only instance methods are dynamically bound:
- A static method with the same signature in a subclass hides the superclass method; it doesn't override it. Which one runs depends on the declared type. (Making a static method override an instance method, or the reverse, is a compile error:
m() in B cannot override m() in A, with the detailoverriding method is staticoroverridden method is static.) - Fields aren't polymorphic either. A subclass field with the same name hides the superclass field, and the declared type picks which one you see. Avoid hiding fields; it only causes confusion.
| Member | Bound | Chosen by |
|---|---|---|
| instance method (not private/final) | dynamically, at run time | actual type of the object |
private, final, static method, constructor | statically, at compile time | declared type |
| overloaded method variant | at compile time | declared types of the arguments |
| field | at compile time | declared type |
Overriding also restricts exceptions: an overriding method can't declare broader checked exceptions than the method it overrides (see the exceptions part).
All of It in One Program
public class Solution {
@SuppressWarnings("static") // e.category() below is a deliberate bad example
public static void main(String[] args) {
Employee e = new Employee("Omar", 52000);
System.out.println(e.getSalary());
e = new Manager("Priya", 91000, 6500); // OK: a Manager is an Employee
System.out.println(e.getSalary()); // dynamic binding: Manager.getSalary
// overloading is decided at compile time, overriding at run time
Printer p = new Printer();
p.print(e); // declared type Employee
// static methods and fields are not polymorphic
System.out.println(e.category() + " " + e.kind);
// covariant return type
Manager m = new Manager("Noor", 88000, 0);
Manager standIn = m.getStandIn(); // no cast needed
System.out.println(standIn.getName());
// arrays are covariant -- and check stores at run time
Manager[] managers = new Manager[10];
Employee[] staff = managers; // legal
try {
staff[0] = new Employee("Omar", 52000);
} catch (ArrayStoreException ex) {
System.out.println("ArrayStoreException: " + ex.getMessage());
}
}
}
class Employee {
String kind = "employee";
private final String name;
private final double salary;
Employee(String name, double salary) { this.name = name; this.salary = salary; }
public String getName() { return name; }
public double getSalary() { return salary; }
public Employee getStandIn() { return new Employee("Temp Cover", 1); }
public static String category() { return "staff"; }
}
class Manager extends Employee {
String kind = "manager"; // hides Employee.kind (avoid this!)
private final double bonus;
Manager(String name, double salary, double bonus) { super(name, salary); this.bonus = bonus; }
@Override public double getSalary() { return super.getSalary() + bonus; }
@Override public Manager getStandIn() { return new Manager("Deputy Lead", 2, 0); }
public static String category() { return "management"; } // hides, doesn't override
}
class Printer {
void print(Employee e) { System.out.println("print(Employee): " + e.getSalary()); }
void print(Manager m) { System.out.println("print(Manager): " + m.getSalary()); }
}
52000.0
97500.0
print(Employee): 97500.0
staff employee
Deputy Lead
ArrayStoreException: Employee
Look at the third line: overload resolution chose print(Employee) from the declared type, and inside it dynamic binding still called Manager.getSalary(). The fourth line shows that e.category() and e.kind follow the declared type Employee. (Calling a static method through an instance, as in e.category(), is legal but misleading; write Employee.category().)
Common questions
Is dynamic binding slow? Very rarely. The JVM uses method tables, and the JIT compiler inlines calls when a call site sees only one or two classes in practice. Such monomorphic and bimorphic call sites are the common case. Design for clarity, and measure before worrying about virtual calls.
Why does print(Employee) get called when I pass a Manager stored in an Employee variable?
Overload resolution happens at compile time and uses the declared types of the arguments. Only the object that the method is called on gets dynamic dispatch. If you need behaviour that depends on the runtime type of an argument, use overriding on that argument (arg.describe()) or a pattern-matching switch.
Can a private method be overridden?
No. A private method isn't visible in the subclass, so a method with the same signature in the subclass is an unrelated new method, and calls inside the superclass still go to the private version. @Override on such a method is a compile error, which is another reason to use the annotation.
Should I use overriding or a sealed hierarchy with switch?
Use overriding when new subclasses will keep appearing and each one should bring its own behaviour. Use a sealed hierarchy with pattern matching when the set of subtypes is fixed and you keep adding new operations. Each new operation is then one exhaustive switch, checked by the compiler.
Why are arrays covariant if it is unsafe?
Before generics (Java 5), covariance was the only way to write general methods such as Arrays.sort(Object[]). The runtime ArrayStoreException check is the price paid for that. Generic collections were designed to be invariant, so these errors are caught at compile time instead.
Summary
- Is-a rule / substitution principle: a subclass object can be used wherever a superclass object is expected. Object variables are polymorphic.
- The declared type determines which methods you may call. The actual type determines which override runs (dynamic binding).
- A superclass reference can't be assigned to a subclass variable without a cast.
- Arrays are covariant. Every array checks stores at runtime and throws
ArrayStoreExceptionfor incompatible elements. - Method calls: collect candidates → overload resolution on declared argument types → static binding for private/static/final/constructors, otherwise dynamic binding via method tables.
- Overrides must keep the signature, may use a covariant return type, and can't reduce visibility. Static methods and fields are hidden, not overridden.
- Dynamic binding lets you add subclasses without changing or recompiling code that uses the superclass.
Practice Questions
Employee e = new Manager(...); Which compiles: e.getSalary(), e.setBonus(100)? Which getSalary runs?
e.getSalary() compiles, because Employee declares it, and Manager.getSalary() runs (dynamic binding on the actual type). e.setBonus(100) doesn't compile: the declared type Employee has no setBonus.
Object[] arr = new String[2]; arr[0] = 42; Does this compile? What happens at runtime?
It compiles, since arrays are covariant and Integer is an Object. At runtime, the array knows it's a String[], so the store throws ArrayStoreException: java.lang.Integer.
Class A has void show(Object o) and void show(String s). With Object x = "hi"; which method does a.show(x) call?
show(Object). Overload resolution uses the declared type of the argument (Object) at compile time. The argument's runtime type doesn't matter.
Which methods are bound statically, and why?
Private, static and final methods and constructors. None of them can be overridden, so the compiler knows the exact target. All other instance methods are bound dynamically.
The superclass has protected Animal reproduce(). Which overrides are legal in Dog: public Dog reproduce(), Animal reproduce() (no modifier), protected Object reproduce()?
public Dog reproduce() is legal (wider access, covariant return). Animal reproduce() with package access is illegal (weaker than protected). protected Object reproduce() is illegal: Object isn't a subtype of Animal, so the return type is incompatible.
Previous: Java Inheritance: Superclasses, Subclasses and Method Overriding
Next: Java final Classes and Methods, Casting, instanceof Patterns and protected Access
Related reading
- Java Inheritance: Superclasses, Subclasses and Method Overriding
- Java Class Design Hints: Writing Clean, Maintainable Classes
- Java Package Access and the Class Path
- Java Records: Compact Data Classes with Canonical and Compact Constructors
- Java static Fields and Methods: Class Variables, Constants, Factory Methods and main

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.