Java Dispatch Rules and Choosing Between Monolith and Microservices
System DesignModel answerLast updated
Explain how Java decides which method runs (overriding versus overloading) and weigh a single deployable application against a set of independent services, including how to migrate.
This is a two-part conceptual question. Answer both parts in prose, with a short code sample where it helps.
Part 1: How Java chooses which method to run
Define polymorphism and describe the forms it takes in Java. Explain how the compiler and the JVM together decide which method body executes for a given call. Include a brief code example in which a reference of a parent class or interface type holds objects of different subclasses.
Your answer should address:
- Overriding and dynamic dispatch at runtime, compared with overload resolution at compile time.
- Which members do not take part in runtime dispatch (static methods, private methods, final methods and fields) and the reason for each.
- The design benefit of programming against a supertype.
Part 2: Monolith or microservices
Compare a monolithic architecture with a microservices architecture. Say when you would pick each one and what it costs to move from the first to the second.
Your answer should address:
- Deployment, scaling, fault isolation and freedom to choose technologies.
- The price of distribution: network failures, keeping data consistent across services, observability and operational load.
- A recommendation for a concrete scenario of your choosing, plus a step-by-step migration path.
You may state your assumptions about the product, team size or stage up front.
Hints
Hint 1
For Part 1, separate what is decided at compile time (which method signature is selected, based on the static types of the arguments) from what is decided at run time (which implementation of that signature runs, based on the actual object type).
Hint 2
Ask of each member kind whether it is looked up through the object's runtime class. Static methods and fields are resolved by the declared type, private methods are not visible to subclasses, and final methods are forbidden from being overridden.
Hint 3
For Part 2, do not declare a winner in the abstract. Tie your recommendation to team size, how independent the business domains are, and how uneven the load is, then describe a gradual extraction instead of a rewrite.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Polymorphism in Java
Definition. Polymorphism means one interface, many behaviors: code written against a general type works with any specific type that conforms to it. Java offers two main forms.
1. Runtime polymorphism (overriding and dynamic dispatch). A subclass supplies its own body for an inherited instance method. When the call is made through a supertype reference, the JVM picks the implementation using the object's actual class, not the reference's declared type. It does this with virtual method dispatch (invokevirtual / invokeinterface), typically through a per-class method table.
2. Compile-time polymorphism (overloading). Several methods share a name but differ in parameter lists. The compiler selects one using the static types of the arguments, via widening, boxing and varargs phases in that order. The runtime type of an argument plays no role.
interface Shape { double area(); }
class Circle implements Shape {
private final double r;
Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * r; }
}
class Rect implements Shape {
private final double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
public double area() { return w * h; }
}
class Printer {
void show(Shape s) { System.out.println("shape " + s.area()); }
void show(Circle c) { System.out.println("circle " + c.area()); }
}
Shape s = new Circle(2);
new Printer().show(s); // prints "shape ..." : overload chosen from static type Shape
s.area(); // Circle.area() runs : override chosen from runtime type
The last two lines show the contrast: the overload was fixed at compile time from the declared type Shape, while area() was resolved at run time to Circle.
What does not dispatch dynamically
- Static methods belong to the class and are hidden, not overridden. The declared type decides which one runs.
- Private methods are not inherited, so a subclass method of the same name is unrelated. Calls are bound directly.
- Final methods cannot be overridden by design, which also lets the JIT inline them freely.
- Fields are never polymorphic. Access uses the declared type, so a subclass field with the same name hides the parent field instead of replacing it.
Rules worth stating. An override must keep the signature, may not narrow access, may return a covariant type, and may not throw broader checked exceptions. @Override makes the compiler verify this. Calling an overridable method from a constructor is a classic trap, because the subclass version may run before the subclass fields are initialized.
Benefit. Callers depend on abstractions, so new implementations can be added without editing existing code (open/closed principle). It also makes testing easier, since a fake can stand in for a real implementation.
Part 2: Monolith versus microservices
Assumed scenario. A new e-commerce product with a team of about eight engineers.
| Dimension | Monolith | Microservices |
|---|---|---|
| Deployment | One artifact, simple pipeline, but every change redeploys everything | Independent deploys per service, but many pipelines |
| Scaling | Scale the whole app together | Scale only hot services (for example search) |
| Fault isolation | A memory leak or bug can take everything down | Failures can be contained, if timeouts and circuit breakers exist |
| Technology | One stack | Per-service choice, at the cost of fragmentation |
| Calls | In-process, nanoseconds, no partial failure | Network calls, milliseconds, retries, timeouts |
| Data | One database, ACID transactions | Database per service, eventual consistency |
| Debugging | One stack trace | Needs distributed tracing, correlation IDs, centralized logs |
| Team fit | Small teams, shared context | Many teams needing autonomy |
Costs of distribution.
- Network failure: every remote call can time out, duplicate or partially succeed. You need idempotency, retries with backoff, and circuit breakers.
- Consistency: cross-service business operations cannot use a single transaction. Use sagas with compensating actions, or the outbox pattern for reliable event publishing, and accept eventual consistency.
- Observability: tracing, metrics and structured logs become mandatory, not optional.
- Operations: service discovery, configuration, versioned APIs, contract testing and container orchestration all add headcount and cost.
Recommendation. For eight engineers and an unproven domain, start with a well-structured modular monolith: clear module boundaries, each module exposing an interface and owning its tables, with no cross-module joins. Move to microservices when there is concrete pain: teams blocking each other's releases, one component needing very different scaling, or a need for different runtime characteristics.
Migration path (strangler approach).
- Enforce module boundaries inside the monolith and remove shared-table access.
- Pick the best candidate (high load or high change rate, few dependencies), and put it behind an interface.
- Extract it as a service, route traffic gradually through a gateway, and keep the old code path as a fallback.
- Give it its own database, synchronizing via events during the transition.
- Add tracing, SLOs and alerts before extracting the next one.
Link between the parts. The interface-based design from Part 1 is the seam that makes extraction cheap. If callers depend on an interface, the in-process implementation can later be replaced by a remote client implementing the same interface, with no change to callers. Keep in mind that the remote version has different failure semantics, so the interface should be designed with that in mind (coarse-grained calls, explicit errors).
Common mistakes
- Saying overloading is runtime polymorphism, or that fields can be overridden.
- Claiming static methods are overridden.
- Presenting microservices as universally better, or ignoring data consistency.
- Splitting into services by technical layer instead of by business capability, producing a distributed monolith.
- Migrating with a big-bang rewrite instead of incremental extraction.