I just have a quick question as I couldn't find any concrete answers on the web. Does having a private static inner class promote loose or tight coupling between it and the outer class in Java?

Thanks for your help in advance, appreciate it!!

有帮助吗?

解决方案

Having a private static inner class permits tight coupling between it and the outer class in Java. It also permits loose coupling. Why? Because coupling requires more than access.

However, it should be understood that loose coupling isn't always the goal. Oh sure it provides flexibility when achieved but that comes with a cost. There are excellent designs that greatly couple inner and outer classes.

One of my favorites is Joshua Blochs Builder Pattern. Tons of coupling but it simplifies construction by simulating named parameters in a language that lacks them. Yes, it's a pain to add new fields but you get fluent construction and an immutable object out of the deal. Also, by sticking the two highly coupled classes together in the same file it makes it easier to manage the coupling.

So please understand. Just because code has been separated into two classes doesn't mean those two classes have to treat each other like strangers. There are many different kinds of valid relationships between classes.

许可以下: CC-BY-SA归因
scroll top