Interfaces — Interview Q&A¶
50 questions on interface design, default methods, functional interfaces, sealed types, and dispatch.
Section A — Basics (1-10)¶
Q1. What is an interface in Java? A: A reference type that declares a contract — methods (and possibly default impls, static methods, constants) — that classes can implement to participate in that contract.
Q2. Can a class implement multiple interfaces? A: Yes. A class can extend at most one class but implement many interfaces.
Q3. Can an interface have instance fields? A: No. All fields in an interface are implicitly public static final constants.
Q4. Can an interface have a constructor? A: No. Interfaces don't have instance state, so there's nothing to construct.
Q5. What's a default method? A: A method in an interface with a body, marked default. Implementing classes inherit it unless they override.
Q6. When were default methods added? A: Java 8 (2014). Enabled adding methods to interfaces without breaking existing implementations.
Q7. What's a static method on an interface? A: A method declared static with a body, scoped to the interface. Java 8+. Used for factories, utilities.
Q8. What's a private interface method? A: A helper method inside an interface, accessible only by other methods in the same interface. Java 9+. Used to share code among default methods.
Q9. What's a functional interface? A: An interface with exactly one abstract method (excluding Object methods). Used as the target type for lambdas and method references.
Q10. What's the @FunctionalInterface annotation? A: A compile-time check: the compiler errors if the annotated interface doesn't have exactly one abstract method.
Section B — Resolution (11-20)¶
Q11. How does Java resolve conflicting default methods? A: Class chain wins over interface. Among interfaces, the more specific (sub-interface) wins. Otherwise, compile error — must override and disambiguate.
Q12. How do you call a specific interface's default method? A: Interface.super.method() — explicit qualifier.
Q13. What's the diamond problem? A: When a class inherits the same method from two paths, ambiguity arises. Java forbids multi-class inheritance to avoid it; for interfaces with conflicting defaults, Java requires explicit resolution.
Q14. Can an interface extend another interface? A: Yes. interface B extends A. B inherits all of A's methods.
Q15. Can an interface extend multiple interfaces? A: Yes. interface C extends A, B.
Q16. Can an interface extend a class? A: No. Interfaces can only extend other interfaces.
Q17. Are interface methods polymorphic? A: Yes. Interface method calls use invokeinterface (or invokevirtual since Java 8 for default methods), dispatching dynamically.
Q18. Can a class override a default method? A: Yes. The override takes precedence; the default is ignored for that class.
Q19. Can you call a parent interface's default after overriding? A: Yes. Parent.super.method() from the override.
Q20. What's the resolution rule when class and interface define same method? A: Class wins. The class's method is used; the interface's default is shadowed.
Section C — Modern features (21-30)¶
Q21. What's a sealed interface? A: An interface with a permits clause restricting which classes can implement it. Java 17+.
Q22. Why use a sealed interface? A: To close the type hierarchy, enabling exhaustive pattern matching and preserving invariants.
Q23. What's the syntax for a sealed interface? A:
Q24. What modifier must permitted impls use? A: final, sealed, or non-sealed — must be one of these.
Q25. How does pattern matching switch use sealed interfaces? A: The compiler verifies exhaustiveness — every permitted variant must be handled. Adding a variant breaks every switch until updated.
Q26. What are records and how do they relate to interfaces? A: Records are immutable data carriers (Java 14+). They commonly implement sealed interfaces to form algebraic data types.
Q27. What's a marker interface? A: An interface with no methods, used to "tag" a class as having a property. E.g., Serializable, Cloneable. Modern Java prefers annotations.
Q28. What's the SPI / ServiceLoader pattern? A: Service Provider Interface — define an interface, list implementations in META-INF/services/Interface (or provides ... with ... in module-info), ServiceLoader.load(Interface.class) returns instances.
Q29. Can a hidden class implement an interface? A: Yes — that's how lambdas work. The hidden class generated by LambdaMetafactory implements the target functional interface.
Q30. What are common functional interfaces in java.util.function? A: Function<T, R>, Predicate<T>, Consumer<T>, Supplier<T>, BiFunction, UnaryOperator, BinaryOperator, plus primitive specializations (IntFunction, LongPredicate, etc.).
Section D — Performance (31-40)¶
Q31. Is invokeinterface slower than invokevirtual? A: Marginally — itable search vs vtable index. Both are inline-cached. Typically <10% difference, often unmeasurable.
Q32. How do lambdas compile? A: To invokedynamic with LambdaMetafactory.metafactory as bootstrap. First invocation generates a hidden class implementing the functional interface.
Q33. Are non-capturing lambdas allocated per call? A: No. Cached after first invocation; same instance used.
Q34. Are capturing lambdas allocated? A: Yes, per evaluation. Often eliminated by escape analysis.
Q35. Why might a @FunctionalInterface be slower than an anonymous class? A: After warmup, identical. Before, anonymous class is loaded eagerly; lambda is generated lazily on first call. So anonymous classes have lower first-call cost; lambdas are smaller in static bytecode.
Q36. What is "monomorphic" interface dispatch? A: A call site that has only ever seen one receiver class. JIT inlines as if direct.
Q37. What is "megamorphic" interface dispatch? A: 3+ receiver classes. JIT falls back to itable lookup; no inlining. Slower.
Q38. How do you keep call sites monomorphic? A: Avoid 5+ implementations per interface in hot paths. Use sealed interfaces. Use final on leaf classes.
Q39. What's the cost of pattern matching switch over sealed interface? A: After warmup, ~1-2 ns per dispatch. Uses an invokedynamic-generated classifier.
Q40. Can interfaces in JPMS modules be loaded lazily? A: Yes. The JVM loads classes on first use. ServiceLoader providers are loaded only when iterated.
Section E — Design (41-50)¶
Q41. When use abstract class vs interface? A: Abstract class for shared state + behavior; interface for pure capability/contract. Default to interface.
Q42. What's the Interface Segregation Principle? A: Don't force clients to depend on methods they don't use. Split fat interfaces into smaller, role-focused ones.
Q43. Why are Java collections defined as interfaces? A: To allow multiple implementations (ArrayList, LinkedList, CopyOnWriteArrayList) and let callers depend only on the contract.
Q44. How do you add a method to an interface without breaking implementations? A: Make it a default method with a sensible default. Implementations get the default; can override if better.
Q45. Can a default method modify state? A: It can call mutating methods on this, but the interface itself has no instance state to modify. Defaults usually compose other interface methods.
Q46. What's a "rich" interface? A: An interface where the abstract method is small and many useful operations are provided as defaults composing the abstract one. Stream, Comparator, Predicate are examples.
Q47. Why might you avoid instanceof checks across interfaces? A: Suggests poor abstraction — the user is decoding which "real type" lurks. Better: extend the interface with a method that handles the variation polymorphically. Or use sealed + pattern matching.
Q48. What's the strategy pattern in interfaces? A: Define an interface for the algorithm, implement multiple variants, inject the chosen variant into the user. Classic way to decouple algorithm from user.
Q49. How does Spring use interfaces? A: Beans are typically declared as interface types; Spring injects the concrete impl. Supports easy mocking, multiple implementations (qualifiers), and aspect-oriented proxy generation.
Q50. What's the trend in modern Java interface design? A: Smaller interfaces, default methods for evolution, sealed interfaces for closed hierarchies, pattern matching for type-driven dispatch, records as algebraic data type carriers.
Bonus (51-55)¶
Q51. Can you mix default and static methods in the same interface? A: Yes. Both have bodies. Static is on the interface itself; default is inherited by impls.
Q52. What's the difference between Optional and Stream as functional contracts? A: Optional = at most one value; Stream = sequence of values. Both have map, filter, etc., but Optional is bounded and synchronous.
Q53. How would you migrate from a class-based hierarchy to interfaces? A: Extract the public API as an interface; classes implement it. Tests depend on interface; production code injects impl. Branch by abstraction.
Q54. What's an "open" vs "closed" interface? A: Open: anyone can implement. Closed (sealed): only listed types can implement. Open is for plugins; closed for type-safe variants.
Q55. When is @FunctionalInterface redundant? A: When the interface clearly has one abstract method and is documented for lambda use. The annotation enforces this — useful for evolution safety. Not strictly required.
Use this list: spread over multiple sessions. Strong candidates explain the why behind each rule.