Polymorphism
Полиморфизм
Code can use the same operation with values of different types. For example, calling `draw()` on a circle and a square uses the same code at the call site, but each shape draws itself differently.
Why it matters
Say a report generator needs to write output to a file in production and collect it in memory during tests. Rather than give the generator a branch for each destination, give it a ReportSink with a write method. The generator only needs to know how to call write; each sink decides what writing means. This is subtype polymorphism, the kind most often discussed in object-oriented programming.
How dispatch works
In Java, the declared type of a variable tells the compiler which methods the caller can use. For an overridable instance method, the actual object determines which implementation runs. This second step is called dynamic dispatch. The following example uses two lambdas to supply implementations of the same interface:
interface ReportSink {
void write(String text);
}
class Reports {
static void publish(ReportSink sink) {
sink.write("Daily report");
}
public static void main(String[] args) {
ReportSink console = text -> System.out.println(text);
var buffer = new StringBuilder();
ReportSink inMemory = text -> { buffer.append(text); };
publish(console); // Prints the report
publish(inMemory); // Appends it to the buffer
}
}
Both calls go through exactly the same publish method. To support a file sink, add an implementation and pass it in. The code that selects the destination might change, but publish doesn't need to.
Other forms of polymorphism
Parametric polymorphism lets one implementation work across types. A generic first(List<T> items) method can return a T from a nonempty list without caring whether the elements are strings or dates. In contrast, ad hoc polymorphism provides different implementations of an operation for particular types. Method overloading is a familiar example: Java resolves a call to format(int) or format(String) at compile time, rather than looking at an object's runtime class to pick an overload.
Design trade-offs and interview questions
A shared signature is only half the job. Implementations must also honor the contract callers rely on. If write promises to report a failed write, a sink that silently drops output is not a valid substitute. Interfaces are useful when implementations need to vary independently of callers; a small conditional may be clearer when the alternatives are fixed and local.
Interviewers often give you a variable declared as an interface or base class and ask what a call prints. Work in two steps: identify the method signature selected at compile time, then, if it's a dynamically dispatched call, identify the implementation on the actual object. That distinction explains why changing a variable's declared type can affect overload resolution without changing the object it refers to.