Re:All New Java Language Features Since Java 21
by pico303 on Saturday September 06, 2025 @11:43PM
(#45155210)
It’s not about swapping implementations, like the original poster suggested, so that you can later come in and swap out different implementations in a local sense. Interfaces are used to decouple parts of an application; for example mocking test interfaces. Another way to look at it is that interfaces are a contract that needs to be fulfilled.
Declaring a local variable as an interface to hide functionality so you can swap out functionality later is misunderstanding the fundamental theories around interfaces. Your variable should be whatever the function or method returns. If you want to abstract the type so it can be swapped out, create a function that returns an abstract type. Don’t tell the HashMap constructor it did the wrong thing. Now that I think about it, I’d recommend you use “var” in all cases, and not try to redefine the return values from a function.
I also like the nudge it gives you to use only the higher level methods, rather than the ones specific to the subclass unless they're needed. That also improves flexibility.