Java Method Dispatch and Service Architecture Trade-offs
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Prompt
During a backend engineering interview, you are asked to walk through two core software engineering topics—one focused on Java language mechanics and one on system architecture:
- Java Polymorphism & Method Resolution: Define polymorphism in Java, contrast how the compiler and the JVM select which method body runs across overloaded versus overridden methods, identify which class members cannot participate in runtime overriding (and why), and illustrate subtype polymorphism with a concise Java snippet.
- Single-Process Monoliths vs. Distributed Services: Compare building and operating a unified monolithic application against splitting a platform into independent microservices. Weigh how each approach affects release cadence, scaling, failure boundaries, cross-service data integrity, and day-to-day operational load, then explain when you would choose each model and how to split an existing monolith safely over time.
Scope & Expectations
- Clearly separate what
javacbinds at compile time using declared reference types from what the JVM dispatches at run time using the receiver's concrete class, including rules forstatic,private,finalmethods, constructors, and fields. - Provide a concrete Java interface or base-class example demonstrating why subtype polymorphism keeps caller code extensible without type-switching branches.
- Pair every advantage of distributed services (independent deployments, targeted scaling, isolated runtimes) with its real-world cost (network latency, partial failures, eventual consistency, distributed tracing, and per-service tooling).
- Ground your architectural recommendation in team topology and domain maturity, and outline a low-risk, step-by-step migration strategy rather than a full rewrite.
Step-by-step walkthrough
What polymorphism means and Java's two-stage decision
Polymorphism (from Greek for "many forms") means writing one piece of code that can work with objects of many different classes through a shared superclass or interface. Instead of writing separate logic for every concrete type, a caller invokes
payment.feeCents(amount)once, and each concrete class provides its own calculation.In Java, every method call is resolved in two distinct stages. Stating this two-stage split upfront makes every rule and edge case in the language discussion fall naturally into place:
- At compile time (
javac), the compiler looks only at static (declared) types — the types written on the variable declarations in source code. Using those declared types, it checks access permissions and picks one exact method signature (the method name and parameter types). Choosing among several methods that share a name but take different parameter lists is method overloading (also called compile-time or static polymorphism). - At run time (JVM), for overridable instance methods, the JVM looks at the runtime (actual) class of the receiver — the real object sitting in memory before the dot (
.). It runs that class's implementation of the signature chosen in stage 1. This is method overriding powered by dynamic dispatch (runtime polymorphism).
Source call: receiver.process(arg) Stage 1 (Compile time - javac) Stage 2 (Run time - JVM) Reads declared types of receiver & arg --> Reads actual class of receiver object Picks exact signature: process(Animal) Jumps to Dog.process(Animal) body (Overload resolution happens here) (Dynamic dispatch happens here)Notice the crucial consequence: the runtime types of the arguments inside the parentheses never affect which overload is chosen, whereas the runtime class of the receiver before the dot decides which override runs. (Java also has a third form, parametric polymorphism, via generics like
List<T>, where one class or method operates safely over different type parameters.)- At compile time (
Runtime polymorphism: overriding, dynamic dispatch, and why it helps
A subclass overrides an inherited instance method by defining a method with the exact same name and parameter types. Java enforces four safety rules so callers using the parent type are never surprised:
- The return type must be the same or a narrower subtype (a covariant return type, meaning a subclass
clone()can returnDogwhen the parent returnsAnimal). - The access modifier cannot be more restrictive (for example, overriding a
publicmethod asprotectedis illegal, because a caller holding the parent reference expectspublicaccess). - It cannot throw new or broader checked exceptions (exceptions the compiler forces callers to catch or declare) than the parent method declares.
- Marking the method with
@Overridetells the compiler to fail immediately if you accidentally misspelled the name or mismatched a parameter type.
import java.util.List; interface PaymentMethod { long feeCents(long amountCents); } class CreditCard implements PaymentMethod { @Override public long feeCents(long amountCents) { return amountCents * 2 / 100; // 2% percentage fee } } class BankTransfer implements PaymentMethod { @Override public long feeCents(long amountCents) { return 25; // flat 25-cent fee } } class Checkout { long totalFees(List<PaymentMethod> methods, long amountCents) { long total = 0; for (PaymentMethod method : methods) { // Dynamic dispatch picks CreditCard.feeCents or BankTransfer.feeCents per object total += method.feeCents(amountCents); } return total; } }Trace
totalFees(List.of(new CreditCard(), new BankTransfer()), 10_000)(a $100.00 order): - Iteration 1:methodpoints to aCreditCard, soCreditCard.feeCents(10_000)runs and returns200cents. - Iteration 2:methodpoints to aBankTransfer, soBankTransfer.feeCents(10_000)runs and returns25cents. - Total returned:200 + 25 = 225cents.Why this matters in real code:
Checkoutdepends only on thePaymentMethodinterface. Adding aDigitalWalletclass later requires zero edits toCheckout— satisfying the open/closed principle (code is open for extension with new types, but closed for modification of existing callers). It eliminates brittleif (m instanceof CreditCard) ... else if ...chains scattered across the codebase and lets unit tests pass in lightweight fake implementations.- The return type must be the same or a narrower subtype (a covariant return type, meaning a subclass
Compile-time polymorphism: overload resolution and the classic trap
Method overloading means defining multiple methods with the same name but different parameter types or counts. The compiler picks the winner purely from the declared types of the arguments in three progressively looser phases: (1) exact and widening primitive/reference matches without autoboxing or
varargs, (2) allowing autoboxing/unboxing (convertinginttoInteger), and (3) allowing variable-length argument lists (T...). Within the first phase that finds matches, it selects the most specific parameter type.This short example demonstrates both compile-time overloading and runtime overriding in a single call:
class Animal { String sound() { return "..."; } } class Dog extends Animal { @Override String sound() { return "Woof"; } } class Vet { String check(Animal a) { return "animal says " + a.sound(); } String check(Dog d) { return "dog says " + d.sound(); } } // Trace: Animal pet = new Dog(); String result = new Vet().check(pet); // evaluates to "animal says Woof"Why does
resultequal"animal says Woof"instead of"dog says Woof"? - Stage 1 (check(pet)): The variablepetis declared asAnimal. Even though the object in memory is aDog, the compiler only knowspethas static typeAnimal, so it binds the call to signatureVet.check(Animal). - Stage 2 (a.sound()): Insidecheck(Animal),sound()is an overridable instance method called on receivera. At run timeapoints to aDoginstance, so dynamic dispatch runsDog.sound()and returns"Woof".If you want behavior to vary with an argument's runtime class, move that behavior into an overridden method on the argument itself (like
a.sound()), or use the visitor pattern (a design pattern that chains two virtual method calls so execution depends on the runtime classes of both objects).Members bound statically that never override
Dynamic dispatch applies only to inherited, non-final instance methods visible to the subclass. Everything else is bound using the declared type at compile time:
staticmethods belong to the class itself rather than to any object instance, so there is no runtime receiver object to inspect. Defining astaticmethod with the same signature in a subclass is method hiding, not overriding; calling it through aParentvariable runsParent's version.privatemethods (and package-private methods when the subclass lives in a different package) are invisible to the subclass, so they are never inherited. A method with the same name in the subclass is a brand-new, unrelated method, and calls insideParentstill invokeParent's private method.finalmethods explicitly forbid overriding (the compiler rejects any attempt). Engineers mark methodsfinalwhen subclasses must not break a security check or class invariant.- Fields (instance and static variables) are never polymorphic in Java. Declaring a field with the same name in a subclass hides the parent's field (the object stores two separate slots in memory), and
ref.fieldreads whichever slot matchesref's declared type. - Constructors initialize a specific class and are not inherited, so they cannot be overridden (only overloaded within the same class).
class Parent { String name = "parent"; static String who() { return "Parent.who"; } private String secret() { return "Parent.secret"; } String callSecret() { return secret(); } String hello() { return "Parent.hello"; } } class Child extends Parent { String name = "child"; // hides Parent.name static String who() { return "Child.who"; } // hides Parent.who private String secret() { return "Child.secret"; } // new, unrelated method @Override String hello() { return "Child.hello"; } // true override } // Trace with declared type Parent pointing to runtime object Child: Parent p = new Child(); System.out.println(p.hello()); // "Child.hello" (virtual dispatch on runtime class Child) System.out.println(p.who()); // "Parent.who" (static method uses declared type Parent) System.out.println(p.name); // "parent" (field access uses declared type Parent) System.out.println(p.callSecret()); // "Parent.secret" (private secret() inside Parent is not overridden) System.out.println(((Child) p).name); // "child" (cast changes declared type to Child)Watch out for the constructor trap: never call an overridable method from a constructor. In Java, when
new Derived()runs, the object's runtime class is alreadyDerivedfrom the start, beforeDerived's fields are initialized:- JVM allocates
Derivedand zeroes all fields (itemsstarts asnull). Base()constructor runs first and callsinit(), which dynamically dispatches toDerived.init()whileitemsis stillnull->NullPointerException!Derived's field initializer (items = new ArrayList<>()) would only have run afterBase()finished.
Single-process monoliths vs. distributed services
A monolith packages the entire application into one deployable artifact (such as a single JAR or container) running in one OS process, typically backed by one shared database. A microservices architecture decomposes the system into small, independently deployable services, each owned by a single team, managing its own private database, and communicating over the network via RPC (HTTP/gRPC) or asynchronous message queues.
Monolith (single process, shared DB) Microservices (network hops, isolated DBs) +----------------------------------+ +-----------+ HTTP/gRPC +-----------+ | [Users] -> [Orders] -> [Billing]| | Orders | ----------------> | Billing | | (nanosecond calls) | | Service | (milliseconds) | Service | +-----------------+----------------+ +-----+-----+ +-----+-----+ | | | v v v +---------------+ +-------------+ +-------------+ | Single RDBMS | | Orders DB | | Billing DB | +---------------+ +-------------+ +-------------+Every architectural benefit of microservices comes with a direct engineering tax:
Dimension Monolith Microservices ------------------ -------------------------------------- ----------------------------------------- Deployment One build & release for everything Each service deploys on its own schedule Scaling Replicate the entire app together Scale only hot bottlenecks (e.g., search) Fault isolation A memory leak can crash whole process Failures stay local IF timeouts exist Technology stack One language, runtime, and framework Services can differ (at tooling cost) Module calls In-process calls (~nanoseconds, safe) Network RPCs (~milliseconds, can drop) Data consistency Single-DB ACID transactions Separate DBs; eventual consistency Debugging Single stack trace and log stream Requires distributed tracing across hopsQuantifying the costs of distribution
Interviewers value concrete numbers over vague claims that "networks are unreliable":
- Network availability compounds downward. Suppose one user request synchronously calls 5 microservices in a chain, and each service has
99.9%uptime (0.1%failure rate) with independent failures:
End-to-end success probability: 0.999^5 = 0.99501 (~99.5% availability) Failure rate jumps 5x: from 0.1% to ~0.5% of all requests In a 30-day month (43,200 min): 0.1% = 43 minutes downtime vs 0.5% = 216 minutes (~3.6 hours)- Latency multiplies across hops. Five in-process Java method calls take roughly
25 nanoseconds(5 nseach). Five sequential data-center network calls taking2 mseach (serialization + network + deserialization) add10 milliseconds— roughly 400,000 times slower — and any slow tail latency in one downstream service stalls the caller.
To survive network calls safely, every hop needs timeouts (never wait forever), retries with exponential backoff paired with idempotency keys (unique client-generated IDs stored by the receiver so retrying a timed-out charge never bills the customer twice), and circuit breakers (wrappers that trip open and fail fast when a downstream dependency is failing, preventing thread exhaustion).
- Data consistency loses single-database ACID transactions (database guarantees of Atomicity, Consistency, Isolation, and Durability that commit or roll back everything together). In a monolith, "charge card + mark order paid" is one SQL transaction. Across two services with separate databases, you use a saga: a sequence of local transactions coordinated by events, where a downstream failure triggers explicit compensating actions (such as issuing a refund and marking the order
CANCELLED), and the UI must handle intermediate states likePENDING. - Observability and operational overhead. A single user action spans multiple machines, requiring correlation IDs passed on every request header and distributed tracing (such as OpenTelemetry) to reconstruct the call tree. Every new service also carries a fixed operational tax: its own CI/CD pipeline, alerts, dashboards, schema/API versioning, and on-call rotation.
- Network availability compounds downward. Suppose one user request synchronously calls 5 microservices in a chain, and each service has
Choosing the right architecture and migrating safely
Base your architectural recommendation on team size, release friction, and domain stability rather than hype:
- Choose a modular monolith for a startup, a new product, or 1–3 engineering teams (~5–25 engineers) whose domain rules are still shifting. Keep one deployable unit, but enforce clean package/module interfaces where each module owns its own database tables. Moving a misdrawn boundary is a 10-minute IDE refactor instead of a multi-week cross-service migration.
- Extract microservices when a large organization (10+ teams) suffers from release-train bottlenecks, sharply skewed resource profiles (CPU-heavy fraud scoring vs. low-traffic admin tools), or strict security/compliance boundaries. In a payment platform like Visa, for example, isolating raw cardholder data into a dedicated vault/tokenization service shrinks the number of servers subject to strict PCI DSS security audits, and separating real-time payment authorization from batch settlement lets the latency-critical path scale and deploy independently.
Incremental migration via the strangler fig pattern (named after vines that grow around an old tree and gradually replace it, avoiding a risky "big-bang" rewrite):
- Modularize inside the monolith first: Untangle shared code into clean internal interfaces and stop modules from directly querying each other's database tables.
- Place an API gateway or reverse proxy in front: Route all external traffic through a thin routing layer you control.
- Extract one high-value seam first: Pick a module with low coupling and a concrete reason to be separate, standing up tracing, CI/CD, and alerting along with it.
- Split the data safely: Give the new service its own database, backfill historical rows, keep data synchronized via dual writes or change data capture (streaming database transaction logs), and then switch reads and writes to the new owner.
- Canary traffic gradually: Shadow-test read traffic first, then ramp live traffic from
1% -> 10% -> 100%behind a feature flag for instant rollback. - Delete the dead monolith path and reassess: Stop extracting once the remaining monolith modules no longer hurt team velocity; aligned with Conway's law (system architecture naturally mirrors team communication boundaries), one service per team—or a modular core surrounded by a few extracted services—is often the healthiest steady state.
Intuition & how it works
Think of Java polymorphism like pressing the Play button on a universal remote control. Before your program ever runs, the compiler checks the button labels on the remote's casing (the variable's declared type) to confirm a play(...) button exists with matching inputs — that is compile-time overload resolution. When you actually press the button in your living room, the infrared signal hits whatever real device is sitting in front of you — a TV, a speaker, or a projector — and that specific device runs its own playback logic — that is runtime dynamic dispatch. For the service architecture comparison, picture one big restaurant kitchen under one roof versus five specialized food trucks across town: chefs in one kitchen pass plates across a counter in milliseconds and check one shared pantry, whereas food trucks can update menus and add extra grill trucks independently, at the cost of coordinating multi-item orders over phone lines that can lag or drop.
Without runtime polymorphism, adding one new payment type forces you to find and edit brittle if / else if type-checking chains scattered across dozens of files. Similarly, splitting an early-stage product into microservices on day one replaces fast in-process method calls and single-database transactions with network timeouts, partial data updates, and heavy operational plumbing before your team even knows where the stable domain boundaries belong.
Walk through two tiny examples to see both ideas in action:
- Polymorphism (Animal pet = new Dog(); new Vet().check(pet);): If Vet overloads check(Animal) and check(Dog), the compiler sees pet declared as Animal and locks in signature check(Animal). Inside check, calling a.sound() inspects the real Dog object at run time and invokes Dog.sound(), producing "animal says Woof".
- Architecture ("charge $100 and mark order PAID"): Inside a monolith, both database updates happen in one ACID transaction (an all-or-nothing database operation that either saves both changes or rolls both back on error). Across an Orders service and a Billing service with separate databases, Orders first writes PENDING, sends a message to Billing, transitions to PAID on success, or runs a compensating CANCELLED update if billing fails.
Key points
- Two stages, two types:
javacresolves overloaded signatures at compile time from the declared (static) types of the receiver and arguments; the JVM resolves overridden method bodies at run time from the actual (dynamic) class of the receiver object. Argument runtime types never influence overload selection. - Only visible, non-final instance methods override:
staticmethods and all fields are hidden (bound to the declared type at compile time),privatemethods (and cross-package package-private methods) are not inherited,finalmethods forbid overriding, and constructors are never inherited. - Polymorphism unlocks the open/closed principle: Callers written against an interface (
PaymentMethod) automatically support new implementations (DigitalWallet) without modifying or recompiling caller logic. - Always add
@Override: It turns accidental overloading (such as writingequals(Money)instead ofequals(Object)) into an immediate compiler error. - Microservices trade in-process simplicity for organizational and scaling autonomy: Independent deployments and targeted scaling are paid for in network latency, compounding failure rates (
0.999^5 ≈ 99.5%), eventual consistency via sagas (multi-step workflows with explicit undo actions), distributed tracing, and per-service DevOps overhead. - Start with a modular monolith unless scale or team count demands otherwise: One deployable artifact with strict internal module boundaries gives small-to-medium teams fast refactoring and simple operations, while keeping future service extraction straightforward via the strangler fig pattern (incrementally routing slices of traffic from the old monolith to new services behind a proxy).
Common mistakes
- Claiming method overloading is decided at run time: Overloads are locked into bytecode by
javacbased solely on declared argument types, which is whycheck(pet)callscheck(Animal)even whenpetholds aDog. - Confusing
staticmethod hiding or field hiding with overriding: Accessingp.who()orp.namethrough aParentreference always usesParent's version, even whenppoints to aChild. - Overloading
equalsinstead of overridingequals(Object): Writingpublic boolean equals(Card other)overloadsObject.equals(Object), soHashSetandList.containssilently ignore your method and fall back to reference equality. - Calling an overridable method inside a constructor: Because
super()executes before subclass field initializers run, the subclass override runs against uninitialized (nullor0) subclass fields. - Recommending microservices to a small team "for scalability": A stateless monolith behind a load balancer scales horizontally to high traffic with a fraction of the operational burden.
- Building a "distributed monolith": Splitting code into separate services that still read/write one shared database or require lockstep deployments combines the network fragility of microservices with the tight coupling of a monolith.
- Attempting a big-bang rewrite: Freezing product work for a year to rebuild a monolith from scratch fails far more often than extracting one bounded service at a time.
Follow-up questions
- Under the hood, how does the JVM execute virtual dispatch, and what optimizations allow the JIT compiler to eliminate that overhead? In HotSpot, each class maintains a virtual method table (
vtable) — an array of function pointers where an overriding method occupies the exact same slot index as its parent's method — soinvokevirtualsimply reads the object's class pointer, looks up that fixed index, and jumps (invokeinterfacescans a per-interface table, oritable). At run time, the JIT (Just-In-Time) compiler (which compiles hot bytecode to native machine code) profiles which concrete receiver classes actually appear at each call site. If only one class (monomorphic) or two classes (bimorphic) appear in practice, the JIT emits a tiny class-pointer check and inlines the target method body directly into the caller (eliminating call overhead altogether), falling back to a full table lookup only atmegamorphicsites (3+ receiver types) and safely deoptimizing if a newly loaded class later adds another override. - Do runtime argument types ever determine which overloaded Java method runs? Illustrate a case where developers often mispredict the output. Never —
javacpicks the overload at compile time using only declared types, plus autoboxing rules. Two classic Java traps catch developers off guard: ```java Collection<?> items = new HashSet(); classify(items); // Given classify(Set<?>) and classify(Collection<?>), // javac picks classify(Collection<?>) from items's declared type!
List``
- **When a single business workflow updates state across two services with separate databases, how do you preserve data consistency?** Avoid **two-phase commit (2PC)** (a blocking distributed lock protocol that stalls both services if the coordinator crashes and scales poorly across network hops), and instead use an asynchronous **saga** paired with the **transactional outbox pattern**. The first service writes its local state (Order = PENDING) *and* an outgoing event row into anoutboxtable inside a single local database transaction, and a background relay reliably publishes that event to the second service. Consumers track processed event IDs for idempotency, and if a downstream step (such as inventory reservation or payment capture) fails, an error event triggers a compensating local transaction (refunding payment or settingOrder = CANCELLED`).
- How does a modular monolith work, and under what team or product conditions does it outperform both an unstructured monolith and microservices? A modular monolith is a single deployable application split into domain modules with strictly enforced boundaries (using Java package visibility, Java Platform Module System, or build-time checks like ArchUnit), where each module exposes a narrow public interface and exclusively owns its database tables. Compared to an unstructured "big ball of mud" monolith, changes stay isolated inside one module; compared to microservices, cross-module calls remain fast in-memory calls with single-database ACID transactions and one deployment pipeline. It is the best default when you have one to a few teams, evolving domain boundaries, and no immediate need to scale or deploy individual components on separate hardware or schedules.
Follow-up questions
- Under the hood, how does the JVM execute virtual dispatch, and what optimizations allow the JIT compiler to eliminate that overhead?
- Do runtime argument types ever determine which overloaded Java method runs? Illustrate a case where developers often mispredict the output.
- When a single business workflow updates state across two services with separate databases, how do you preserve data consistency?
- How does a modular monolith work, and under what team or product conditions does it outperform both an unstructured monolith and microservices?
Similar questions
- Build and Explain a Grounded RAG Pipeline
- Navigating a Visa Data Science Initial Recruiter Screen
- Lean Solutions to Complex Problems and Project Decomposition
- Reachable Positive Totals with Limited Coin Counts
- Counting Transitive Clusters in an Adjacency Matrix
- Pair Sum Count Across Two Arrays
More Visa interview questions
- Locate Target in Strictly Increasing Array Medium
- Build and Explain a Grounded RAG Pipeline Medium
- Lean Solutions to Complex Problems and Project Decomposition Medium Pro
- Counting Transitive Clusters in an Adjacency Matrix Medium Pro
- Pair Sum Count Across Two Arrays Medium Pro
- Counting Landmasses on a Read-Only Grid Medium Pro
- Counting Valid Letter-and-Punctuation Tokens Medium Pro
- Order Price Snapshots and 30-Day Spend Indexing Medium Pro
- Architecting an On-Demand Ride Dispatch Backend Medium Pro
- Cyclic Warehouse Package Routing with Closures Medium Pro